From 1dc0550659a5956eaff4310125b292873e8246af Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 6 Oct 2026 20:38:49 +0000 Subject: [PATCH] replace urgency priority queue with strict FIFO Drop the urgency score and interrupt/preempt decisions: intake is now idle -> dispatch, busy -> append to a bounded FIFO queue (RequestQueue). The running process always finishes before the next queued request. - queue.py: UrgencyQueue -> RequestQueue (deque, no weight/age/recency) - scheduler.py: remove _priority_score, _interrupt_choice, urgency constants, and the weight threaded through dispatch/authoring/requeue - dashboard/static/gateway: drop weight + preempted handling - tests + docs updated; flow-main.svg regenerated --- AGENTS.md | 34 +++---- README.md | 50 +++++----- config.example.json | 2 +- docs/flow-main.svg | 4 +- docs/flow.md | 20 ++-- semif_agent/dashboard.py | 4 +- semif_agent/gateway/service.py | 2 +- semif_agent/queue.py | 71 ++++---------- semif_agent/scheduler.py | 145 ++++++++--------------------- semif_agent/static/app.js | 12 +-- semif_agent/static/style.css | 2 - semif_agent/trace.py | 2 +- tests/integration/test_pipeline.py | 13 ++- tests/test_gateway.py | 22 ++--- tests/test_housekeeping.py | 6 +- tests/test_humanize.py | 10 +- tests/test_queue.py | 81 +++++----------- tests/test_skills.py | 34 +++---- 18 files changed, 173 insertions(+), 341 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c65e4c4..423e608 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ Guessing, inventing data, or shipping a toy is always the wrong answer. ## What this is A local desktop CLI agent whose entire control flow is a single decision model -(SemIf). Inputs are scored for urgency, queued, and dispatched through a +(SemIf). Inputs are queued FIFO and dispatched through a skill tree. Nothing is gated out up front: every input is dispatched and inputs that are not requests fall through navigation into the closed `response` tree of canned replies (a request no skill covers authors a skill instead — the @@ -66,10 +66,10 @@ cli.py argparse: run (REPL / --script), dream, skills, status, relabel, dashboard, gateway (command intake), bridge (standalone third-party API bridges) scheduler.py no up-front gate: every input is dispatched - -> choice(tau) -> score -> queue; preempt + requeue; - a skill run paused for input (needs_input) keeps `current` - busy; `answer` routes straight to the pending run, bypassing - gate/score/navigation; draft authoring (title+description by the + -> FIFO queue when busy; a skill run paused for input + (needs_input) keeps `current` busy; `answer` routes straight to + the pending run, bypassing the queue/navigation; draft authoring + (title+description by the small `llm` provider) AND skill-body authoring (codegen) are ASYNC single-slot workers: a create_category/create_skill request is queued, the gate stays free, the category job chains into its @@ -93,7 +93,7 @@ scheduler.py no up-front gate: every input is dispatched operate on the tree via `ctx.admin`; per-category new-skill locks (`locks.new_skill` in the category config) gate creation, with `housekeeping`/`response` hard-locked in code -queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0 +queue.py bounded FIFO request queue (arrival order, max depth) skills.py tree + registry (hardcoded built-ins: the closed `response` canned tree plus the `housekeeping` meta skills), navigation = SemIf choices per level (logged; @@ -187,7 +187,7 @@ console.py OpenCode Console provider: OpenCodeConsoleClient + the log.py decisions.jsonl rows {state, question, options, predicted_probs, selected, observed_outcome, label_source} trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ - preempted/assessed/...); decisions reference run_id in extra + dequeued/assessed/...); decisions reference run_id in extra dream.py NLL of observed outcome per row; weighted CE, accuracy, ECE decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult, Request) @@ -297,7 +297,7 @@ values are yours to choose. ## Roadmap ### v1 (done) -Core loop, urgency queue, skill tree, skill loop with real SemIf assessment +Core loop, FIFO queue, skill tree, skill loop with real SemIf assessment (decision, not generation), decision logging, `dream` cost pass, REPL + JSONL CLI, unit tests (24) + integration tests (2). @@ -374,7 +374,7 @@ CLI, unit tests (24) + integration tests (2). skip their softmax. - **No handle/ignore gate; the `response` tree is the non-request catchall** (Sep 2026; actionability guard Oct 2026): the top-level `_contains_request` - handle/ignore gate is gone. Every input is scored and dispatched; input that + handle/ignore gate is gone. Every input is dispatched; input that is not a request falls through navigation into the closed `response` category, a hardcoded tree of canned replies (`response.greeting`, `response.thanks`, `response.acknowledge`, `response.farewell`, `response.affirm`, and the @@ -490,7 +490,7 @@ CLI, unit tests (24) + integration tests (2). - **Messenger gateway (SimpleX first, then LXMF)** (Sep 2026; LXMF Oct 2026): `python -m semif_agent.cli gateway` runs a dedicated process that connects to one or more transports and feeds authorized DM text through the normal - gate/score/queue/dispatch pipeline; results, authoring questions, and repair + queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. `gateway/base.py` is the transport contract (`GatewayAdapter`, `InboundMessage`, `OutboundMessage`), `gateway/service.py` the platform-aware scheduler glue (single execution slot, @@ -797,8 +797,8 @@ CLI, unit tests (24) + integration tests (2). rides in the code), the error + existing files are fed back, bounded by `codegen.test_max_attempts`. On success the body is materialized (`materialize_skill`), hot-merged, the - leaf's `writing` flag clears, and the **original request is re-queued** at its - scored weight and re-runs navigation onto the new leaf (`skill_requeued`). On + leaf's `writing` flag clears, and the **original request is re-queued** and + re-runs navigation onto the new leaf (`skill_requeued`). On failure (`CodegenError`/`ValueError`) the user is notified, the leaf stays a restartable stub, and the request is NOT re-dispatched. A re-dispatched request whose skill is still unwritten reports the pending write instead of @@ -1021,7 +1021,7 @@ CLI, unit tests (24) + integration tests (2). wake (optionally again on transcription) so the user knows they were heard. **Result-only output**: `VoiceAdapter.result_only` (default true; per-platform config `result_only` overrides) makes `GatewayService` speak just the skill's - result line — queue/urgency chatter is dropped and the `: ok —` wrapper + result line — scheduler bookkeeping is dropped and the `: ok —` wrapper is stripped — so the spoken output is the answer, not the scheduler's internals. Questions, repair offers, approvals, and timer notifications are still spoken. @@ -1043,7 +1043,7 @@ CLI, unit tests (24) + integration tests (2). ownership across an updated request so its completion still routes home. A `needs_input` pause sets `pending_owner` from the pending run's source; the same chat's next message goes straight to `Scheduler.answer` (no - score/navigation). A *different* chat — **including a chat on another + queue/navigation). A *different* chat — **including a chat on another platform** — during that pause is told to wait: the single-slot scheduler must not silently abandon the first chat's run, and one service fronts all adapters so the guard spans them. A background poll calls @@ -1248,9 +1248,9 @@ The bridge read path (`simplex.next_message`) and contact-link lookup - Navigation decisions ARE logged (`navigate:category`, `navigate:leaf` in skills.py) and therefore count toward dream cost. This is intended per the design; don't silently drop them. -- Queue ordering: urgency desc, then FIFO (`seq`). Recency is stored but is NOT - in the sort key (it's anti-correlated with FIFO). Ageing pulls weights toward - the max (1.0) so low items catch up; uniform additive boosts do nothing. +- Queue ordering: strict FIFO (arrival order). There is no urgency score and no + preemption; the running process always finishes before the next queued request + is dispatched. - The decision engine is always real and every `EngineUnavailable` is **fatal**: `submit` records it (`("fatal", ...)`), the scheduler exposes `fatal`, and the CLI prints it and exits non-zero. There is no degraded/soft-error path. diff --git a/README.md b/README.md index 030ee53..7d12a28 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ A successful release of this could be defined by a single question: "Can I use t - [Why this exists (the reasoning)](#why-this-exists-the-reasoning) - [How it works](#how-it-works) - - [The scheduler: choose, score, queue, dispatch](#the-scheduler-choose-score-queue-dispatch) + - [The scheduler: queue and dispatch](#the-scheduler-queue-and-dispatch) - [The skill tree and navigation](#the-skill-tree-and-navigation) - [The skill run loop](#the-skill-run-loop) - [Authoring a new skill](#authoring-a-new-skill) @@ -70,7 +70,7 @@ model entirely: does.) - **Simulated Agile patterns.** A skill is a real integration into the active tool chain for end user satisfaction. It takes existing mail protocols, SimpleX, CalDAV/WebDAV, configured local CLIs, HTTP APIs and your supplied data to produce actions that best fit your query. In the absence of a an existing skill, the skill generation process is activated. Skill generation has four major phases - definition, refinement, coding, testing (unit and integration). Each step in this process has deterministic and probabilistic handling optimized to achieve the stated goal of the user in the context of the platform's core mission. -- **Nothing is gated out up front.** Every input is dispatched and scored. +- **Nothing is gated out up front.** Every input is dispatched. Inputs that are not requests fall through navigation into the closed `response` category — a hardcoded tree of canned replies (`greeting`, `thanks`, `acknowledge`, `farewell`, `affirm`, and the catchall `clarify`). A request no @@ -88,25 +88,23 @@ model entirely: ## How it works -### The scheduler: choose, score, queue, dispatch +### The scheduler: queue and dispatch Implemented in `semif_agent/scheduler.py` and `semif_agent/queue.py`: ``` intake (typed input / messenger gateway / scripted) - └─ choice "should this interrupt the current process?" (SemIf) - ├─ yes → preempt current, requeue it with state preserved - └─ no → score "how urgent?" critical/high/medium/low (SemIf) - └─ urgency priority queue (weight desc, then FIFO) + ├─ idle → dispatch immediately + └─ busy → FIFO queue (arrival order, no priority) ``` -- The **queue** is a max-heap by urgency weight, FIFO within equal weight, with - upward ageing so low-priority items cannot starve (`queue.py`). +- The **queue** is a strict first-in-first-out list of pending requests with a + maximum depth (`queue.py`). There is no urgency scoring and no preemption. - A **skill run paused for input** (`needs_input`) keeps the current slot busy; - an answer routes straight back to the pending run, bypassing - choice/score/navigation. -- A high-priority input can preempt the running process, which re-queues with its - state preserved. + an answer routes straight back to the pending run, bypassing the queue and + navigation. +- The running process always finishes before the next queued request is + dispatched. - Exactly one execution slot. (Concurrency, when it comes, is SemIf's shared-state mode for parallel *decisions* — not parallel process execution.) @@ -200,9 +198,9 @@ worker. It is **asynchronous**, so the gate stays free while either model thinks `codegen.test_max_attempts`. On success the body materializes to `data/skills///`, is -hot-merged, and **the original request is re-queued** at its scored weight and -re-runs navigation onto the new leaf. On failure the leaf stays a restartable -stub. A whole new category runs the same chain deterministically: +hot-merged, and **the original request is re-queued** and re-runs navigation +onto the new leaf. On failure the leaf stays a restartable stub. A whole new +category runs the same chain deterministically: `create_category` → `create_skill` → async body → re-dispatch. A rejected/simulated body is traced (`fidelity_review`), badged `unverified`, @@ -230,8 +228,6 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog** | Phase | File | State injected | Options | | --- | --- | --- | --- | -| `interrupt:choice` | `scheduler.py:279` | request text + `[current process: ]` | `interrupt` / `defer` | -| `priority:score` | `scheduler.py:296` | request text (+ `[current process: …]` when busy) | critical / high / medium / low | | `navigate:category` | `skills.py:682` | request text | every category name (+ `create_category`) | | `navigate:leaf` | `skills.py:736` | request text + current category | every skill name + description (+ `create_skill`) | | `navigate:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) | @@ -362,8 +358,8 @@ fine-tuning loop — it is not yet the fine-tune itself. semif_agent/ cli.py argparse: run / dream / skills / status / relabel / dashboard / gateway / bridge - scheduler.py no up-front gate; choice -> score -> queue -> dispatch; - preempt + requeue; needs_input pauses; async single-slot + scheduler.py no up-front gate; FIFO queue -> dispatch; + needs_input pauses; async single-slot skill authoring worker; fidelity gate; repair loop skill.py observe -> act -> observe -> assess; deterministic summary; pre-act contract collection; resolved-input state @@ -378,7 +374,7 @@ semif_agent/ trace.py runs.jsonl lifecycle events keyed by run_id dream.py NLL / weighted CE / accuracy / ECE cost report decisions.py DecisionRequest / Option / DecisionResult / Request dataclasses - queue.py urgency max-heap (weight desc, FIFO, ageing) + queue.py bounded FIFO request queue dashboard.py stdlib HTTP + JSON API + static UI static/ dashboard frontend (html/js/css) simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge) @@ -504,7 +500,7 @@ Key blocks: | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | | `tau` | decision threshold; `max_reentries` requeue bound | -| `queue` | `max_size`, `age_rate` | +| `queue` | `max_size` | | `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | | `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD, follow-up window | @@ -556,7 +552,7 @@ HF_HOME="$REPO/.runtime/hf" "$REPO/.runtime/venv/bin/python" -m semif_agent.cli Type a request, or one of the meta-commands: ``` -busy mark a current process (so preemption can be demonstrated) +busy mark a current process (so the queue can be demonstrated) idle clear the current process status current process + queue skills skill tree @@ -599,7 +595,7 @@ shares one scheduler/skill store. `--platform` takes a comma-separated list or python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard] ``` -Each platform feeds authorized DM text through the normal gate/score/queue/ +Each platform feeds authorized DM text through the normal queue/dispatch dispatch pipeline. Results, authoring questions and repair offers go back to the originating chat. Config lives under `gateway.` in `config.json`; `enabled` defaults to false. Both transports are **default-deny** — put allowed @@ -638,7 +634,7 @@ address as a contact in your LXMF client and DM it. `gateway --platform voice` turns the machine's microphone into a command front end: an always-on **wake word** (openWakeWord), **speech-to-text** (faster-whisper), and **text-to-speech** (Piper), all local — no cloud. A spoken -command is fed through the same gate/score/queue/dispatch pipeline as a typed or +command is fed through the same queue/dispatch pipeline as a typed or messaged one, and every reply is spoken back. It is a normal gateway adapter, so `needs_input` questions, repair offers, and approvals are spoken and answered by voice too. @@ -668,7 +664,7 @@ python -m semif_agent.cli gateway --platform voice utterance is accepted **without** the wake word for `follow_up_window_s`, so answering a question is conversational. `max_speak_chars` truncates long replies before speaking. `result_only` (default true for voice) speaks only the - skill's result line — queue/urgency bookkeeping is dropped and the + skill's result line — scheduler bookkeeping is dropped and the `: ok —` wrapper is stripped — so the spoken output is the answer, not the scheduler's internals; set it false to speak the full scheduler output. There is no allowlist: the mic is local, so physical access is the @@ -804,7 +800,7 @@ works. ## Roadmap / status -**Done.** Core loop, urgency queue, skill tree, real SemIf assessment, decision +**Done.** Core loop, FIFO queue, skill tree, real SemIf assessment, decision logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` / `create_skill` with the async authoring pipeline (elicitation → body → fidelity → contract → test → auto-run → re-dispatch); tiered config + first-fire diff --git a/config.example.json b/config.example.json index ff12a46..82db0bb 100644 --- a/config.example.json +++ b/config.example.json @@ -10,7 +10,7 @@ "category_tau": 0.75, "action_tau": 0.5 }, - "queue": {"max_size": 100, "age_rate": 0.01}, + "queue": {"max_size": 100}, "engine": { "_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.", "backend": "llamacpp", diff --git a/docs/flow-main.svg b/docs/flow-main.svg index afa413b..0f607f9 100644 --- a/docs/flow-main.svg +++ b/docs/flow-main.svg @@ -1,4 +1,4 @@ -

idle

busy

full

ok

run_queue when idle

yes

no

rejected

covers

yes (response)

no

none

one

many

different

same

yes

no (noop stub)

runnable

yes

answer() bypasses queue

no

yes

answer()

no

yes

no

retry

complete

user confirms

canned category skips assess

Input
REPL text · gateway DM · dashboard submit

Scheduler.submit_request()
create Request, trace 'submit'

current process?

Scheduler._dispatch()

RequestQueue.push
FIFO, bounded

Output: rejected
'queue is full'

Output: queued

navigate()
descend tree, one SemIf choice per level

SemIf choice
phase 'navigate:category'
options = categories + descriptions
+ create_category

winner =
create_category
or tree empty?

CreateCategory

SemIf choice
phase 'navigate:category_scope'
P covers >= category_tau?

category in
CANNED_CATEGORIES?

_navigate_canned
phase 'navigate:response'
closed canned reply tree

_run_skill()

skills in
category?

CreateSkill

sole skill
softmax skipped

SemIf choice
phase 'navigate:leaf'
options = existing skills only

picked skill

SemIf choice
phase 'navigate:intent'
P same >= intent_tau?
sole reuse-vs-create guard

authoring pipeline
see below

leaf still
writing?

Output: error
'body still being written'

Output: error
'no body yet; restart '

SkillRunner.run()
resolve tiered config
global -> category -> skill

contract variable
unresolved?

Output: needs_input
pre_act pause
ask one variable

SemIf choice
phase 'config:record'
record as config vs ask each fire

skill.act(ctx, request)
REAL action via stdlib transport
values from ctx.config

act asks
for input?

Output: needs_input
act pause

SemIf choice
phase 'assess:outcome'
P success >= tau?

success?

deterministic summary
category.name: ok/failed - action_log

SemIf choice
phase 'assess:requeue'
complete vs retry

requeue original request
bounded by max_reentries

SemIf choice
phase 'repair:choice'
retry / repair_skill / ask_user / no_repair

Output: ran
REPL print · gateway reply · dashboard trace

Output: repair offer
surfaced in REPL/dashboard/gateway

\ No newline at end of file diff --git a/docs/flow.md b/docs/flow.md index ff70bb9..ffdd5cb 100644 --- a/docs/flow.md +++ b/docs/flow.md @@ -3,7 +3,7 @@ How one input travels through the agent. Every diamond marked **SemIf** is a real decision-engine call that is logged as a training row; the LLM only ever *generates* (skill drafts, bodies, questions). There is no up-front -handle/ignore gate — every input is scored and dispatched. +handle/ignore gate — every input is dispatched. The diagram is split in two: the **main pipeline** (intake → navigation → run → output) and the **authoring pipeline** (what happens when navigation decides a @@ -23,20 +23,14 @@ flowchart TD SUB --> BUSY{"current process?"} %% ---------- idle path ---------- - BUSY -- "idle" --> SCORE["SemIf score
phase 'score'
How urgent is this?"] - SCORE --> DISPATCH + BUSY -- "idle" --> DISPATCH["Scheduler._dispatch()"] %% ---------- busy path ---------- - BUSY -- "busy" --> INTERRUPT["SemIf choice
phase 'choice'
may this interrupt?"] - INTERRUPT -- "defer" --> SCORE2["SemIf score
phase 'score'"] - SCORE2 --> PUSH["UrgencyQueue.push
max-heap: weight desc, FIFO seq
age pulls low items toward 1.0"] + BUSY -- "busy" --> PUSH["RequestQueue.push
FIFO, bounded"] PUSH -- "full" --> REJECT["Output: rejected
'queue is full'"] - PUSH -- "ok" --> QUEUED["Output: queued
urgency label + weight"] + PUSH -- "ok" --> QUEUED["Output: queued"] QUEUED -. "run_queue when idle" .-> DISPATCH - INTERRUPT -- "interrupt" --> PREEMPT["Abandon pending run
requeue previous at its weight
trace 'preempted'"] - PREEMPT --> DISPATCH["Scheduler._dispatch()"] - %% ---------- navigation ---------- DISPATCH --> NAV["navigate()
descend tree, one SemIf choice per level"] @@ -73,7 +67,7 @@ flowchart TD RESOLVE --> UNRES{"contract variable
unresolved?"} UNRES -- "yes" --> PAUSE1["Output: needs_input
pre_act pause
ask one variable"] - PAUSE1 -. "answer() bypasses gate" .-> RECORD["SemIf choice
phase 'config:record'
record as config vs ask each fire"] + PAUSE1 -. "answer() bypasses queue" .-> RECORD["SemIf choice
phase 'config:record'
record as config vs ask each fire"] RECORD --> RESOLVE UNRES -- "no" --> ACT["skill.act(ctx, request)
REAL action via stdlib transport
values from ctx.config"] @@ -171,8 +165,8 @@ flowchart TD | Stage | Decision (SemIf) | Phase logged | Output | | --- | --- | --- | --- | -| Intake, idle | urgency | `score` | weight → dispatch | -| Intake, busy | interrupt? | `choice` | preempt or queue | +| Intake, idle | — (no decision) | — | dispatch immediately | +| Intake, busy | — (no decision) | — | FIFO queue (arrival order) | | Category | which category | `navigate:category` | category / create | | Category scope | does it cover? | `navigate:category_scope` | descend / create | | Canned | which reply | `navigate:response` | canned line | diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index 0c17950..df6f989 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -111,8 +111,8 @@ def build_status(scheduler: Scheduler) -> dict: else None ) queue = [ - {"id": request.id, "weight": weight, "text": request.text[:80]} - for weight, request in scheduler.queue.items() + {"id": request.id, "text": request.text[:80]} + for request in scheduler.queue.items() ] tau = scheduler.tau queue_max = scheduler.queue.max_size diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index b2716be..4d58c1d 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -83,7 +83,7 @@ def _result_detail(text: str) -> str: def _reply_kind(status: str) -> str: """Classify a scheduler outcome for a result-only front end.""" - if status in ("running", "preempted", "ran"): + if status in ("running", "ran"): return "result" if status == "needs_input": return "question" diff --git a/semif_agent/queue.py b/semif_agent/queue.py index d78e00c..0fd7699 100644 --- a/semif_agent/queue.py +++ b/semif_agent/queue.py @@ -1,83 +1,44 @@ -"""Urgency priority queue. +"""FIFO request queue with a maximum depth. -Items are sorted by descending urgency weight, then FIFO arrival, then most -recent first. Queued items age upward so they cannot starve, and the queue has -a maximum depth. +Requests are dispatched strictly in arrival order: there is no urgency scoring +and no preemption, so the running process always finishes before the next queued +request is picked up. """ from __future__ import annotations -import heapq -import itertools -import time -from dataclasses import dataclass +from collections import deque from typing import Iterator from .decisions import Request -MIN_RECENCY = 0.0 +class RequestQueue: + """A bounded first-in-first-out queue of pending requests.""" -@dataclass -class QueueItem: - weight: float - seq: int - recency: float - request: Request - - def key(self) -> tuple: - return (-self.weight, self.seq) - - -class UrgencyQueue: - """A max-by-urgency priority queue with FIFO/recency tie-breaking.""" - - def __init__(self, max_size: int = 100, age_rate: float = 0.0): + def __init__(self, max_size: int = 100): self.max_size = max_size - self.age_rate = age_rate - self._entries: list[tuple] = [] - self._counter = itertools.count() + self._entries: deque[Request] = deque() - def push(self, request: Request, weight: float, recency: float | None = None) -> bool: - """Insert an item. Returns False if the queue is full.""" + def push(self, request: Request) -> bool: + """Append an item. Returns False if the queue is full.""" if len(self._entries) >= self.max_size: return False - item = QueueItem( - weight=weight, - seq=next(self._counter), - recency=recency if recency is not None else time.time(), - request=request, - ) - entry = (*item.key(), next(self._counter), item) - heapq.heappush(self._entries, entry) + self._entries.append(request) return True def pop(self) -> Request | None: if not self._entries: return None - return heapq.heappop(self._entries)[-1].request + return self._entries.popleft() def peek(self) -> Request | None: if not self._entries: return None - return self._entries[0][-1].request - - def age(self, dt: float = 1.0) -> None: - """Pull queued priorities toward critical so old items catch up.""" - if self.age_rate <= 0: - return - rebuilt = [] - for entry in self._entries: - item = entry[-1] - item.weight += self.age_rate * dt * (1.0 - item.weight) - rebuilt.append((*item.key(), next(self._counter), item)) - self._entries = rebuilt - heapq.heapify(self._entries) + return self._entries[0] def __len__(self) -> int: return len(self._entries) - def items(self) -> Iterator[tuple[float, Request]]: - for entry in sorted(self._entries, key=lambda e: e[:-1]): - item = entry[-1] - yield item.weight, item.request \ No newline at end of file + def items(self) -> Iterator[Request]: + yield from self._entries diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 4c8d650..bb00398 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -1,10 +1,11 @@ -"""The scheduler: choice, score, queue, dispatch. +"""The scheduler: queue, dispatch. -Every SemIf decision (choice, score, navigation, sub-decision) is logged. -A high-priority input can preempt the current process, which requeues with its -state preserved; a deferred input is scored and queued by urgency. There is no -up-front handle/ignore gate: every input is dispatched, and inputs that are not -tasks fall through navigation into the closed `response` tree of canned replies. +Every SemIf decision (navigation, sub-decision) is logged. Input that arrives +while the single execution slot is busy waits in a strict FIFO queue and is +dispatched in arrival order; there is no urgency scoring and no preemption. +There is no up-front handle/ignore gate: every input is dispatched, and inputs +that are not tasks fall through navigation into the closed `response` tree of +canned replies. """ from __future__ import annotations @@ -36,7 +37,7 @@ from .engine import EngineUnavailable, SemIfEngine from .llm import LLMClient from .log import DecisionLog from .provider import ProviderError -from .queue import UrgencyQueue +from .queue import RequestQueue from .skill import SkillRunner from .timers import TimerService from .skills import ( @@ -68,21 +69,11 @@ from .skills import ( ) from .trace import TraceLog -CHOICE_INTERRUPT = "interrupt" -URGENCY_OPTIONS = [ - ("critical", "Immediate danger or critical failure."), - ("high", "Important but not dangerous."), - ("medium", "Should be handled reasonably soon."), - ("low", "Can wait."), -] -URGENCY_WEIGHTS = {"critical": 1.0, "high": 0.75, "medium": 0.5, "low": 0.25} - @dataclass class Process: request: Request skill: str - weight: float @dataclass @@ -107,7 +98,6 @@ class SkillWrite: request: Request category: str draft: SkillDraft - weight: float repair_evidence: dict | None = None # Label for a corrective rewrite: "run_failure" (repair loop), "fidelity", # "test", or "manual" (a user-requested regen). @@ -127,7 +117,6 @@ class DraftAuthor: request: Request category: str | None - weight: float kind: str approved: bool = False @@ -262,9 +251,8 @@ class Scheduler: self.contract_search = bool( (codegen_cfg.get("contract_search", {}) or {}).get("enabled", True) ) - self.queue = UrgencyQueue( + self.queue = RequestQueue( max_size=int(config.get("queue", {}).get("max_size", 100)), - age_rate=float(config.get("queue", {}).get("age_rate", 0.0)), ) self.skills = build_skills(config) + build_housekeeping_skills() self.tree = build_tree(self.skills) @@ -326,38 +314,6 @@ class Scheduler: self._fatal = f"decision engine not available: {exc}" return self._fatal - # ---- decision templates (all real SemIf, all logged) ---- - - def _interrupt_choice(self, request: Request, current: Process) -> bool: - decision = DecisionRequest( - state=f"{request.text} [current process: {current.skill}]", - question="Should this be allowed to interrupt the current process?", - options=[ - Option(CHOICE_INTERRUPT, "Yes, interrupt the current process."), - Option("defer", "No, wait until the current process finishes."), - ], - ) - result = self.engine.call(decision) - self.log.append( - decision, - result, - extra={"phase": "choice", "current": current.skill, "run_id": request.id}, - ) - return result.prob(CHOICE_INTERRUPT) >= self.tau - - def _priority_score(self, request: Request, current: str | None = None) -> tuple[float, str]: - decision = DecisionRequest( - state=f"{request.text} [current process: {current}]", - question="How urgent is this request?", - options=[Option(option_id, description) for option_id, description in URGENCY_OPTIONS], - ) - result = self.engine.call(decision) - self.log.append( - decision, result, extra={"phase": "score", "run_id": request.id} - ) - label = result.selected - return URGENCY_WEIGHTS[label], label - # ---- intake ---- def submit(self, text: str, source: str = "typed") -> tuple[str, str]: @@ -388,50 +344,31 @@ class Scheduler: self.trace.append("submit", request.id, text=text, source=source) if self.current is None: - weight, label = self._priority_score(request) - self.current = Process(request=request, skill="(scheduling)", weight=weight) + self.current = Process(request=request, skill="(scheduling)") try: - outcome = self._dispatch(request, weight=weight) + outcome = self._dispatch(request) finally: if self.pending is None: self.current = None if outcome.kind == "needs_input": return "needs_input", outcome.summary, request.id self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) - return "running", f"[{label}] {outcome.summary}", request.id + return "running", outcome.summary, request.id - interrupt = self._interrupt_choice(request, self.current) - if interrupt: - if self.pending is not None: - self.trace.append("pending_abandoned", self.pending.request.id) - self.pending = None - previous = self.current - previous.request.resume["from_skill"] = previous.skill - self.queue.push(previous.request, previous.weight) - self.current = Process(request=request, skill="(scheduling)", weight=1.0) - self.trace.append("preempted", request.id, preempted=previous.skill) - outcome = self._dispatch(request, weight=1.0) - if outcome.kind == "needs_input": - return "preempted", f"interrupted {previous.skill}; {outcome.summary}", request.id - self.current = None - self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) - return "preempted", f"interrupted {previous.skill}; {outcome.summary}", request.id - - weight, label = self._priority_score(request, current=self.current.skill) - ok = self.queue.push(request, weight) + ok = self.queue.push(request) if not ok: self.trace.append("rejected", request.id, reason="queue is full") return "rejected", "queue is full", request.id - self.trace.append("queued", request.id, weight=weight, label=label) - return "queued", f"urgency {label} (weight {weight:.2f})", request.id + self.trace.append("queued", request.id) + return "queued", "queued", request.id def busy(self, text: str, skill: str = "(driving)") -> None: - """Set a fake in-progress process so the choice/score path is exercised.""" + """Set a fake in-progress process so the queue path is exercised.""" with self._lock: if self.pending is not None: self.trace.append("pending_abandoned", self.pending.request.id) self.pending = None - self.current = Process(request=Request(text, source="busy"), skill=skill, weight=1.0) + self.current = Process(request=Request(text, source="busy"), skill=skill) def idle(self) -> None: with self._lock: @@ -456,9 +393,9 @@ class Scheduler: break request = self.queue.pop() self.trace.append("dequeued", request.id) - self.current = Process(request=request, skill="(scheduling)", weight=0.0) + self.current = Process(request=request, skill="(scheduling)") try: - outcome = self._dispatch(request, weight=0.0) + outcome = self._dispatch(request) except EngineUnavailable as exc: self._mark_fatal(exc) results.append(("fatal", self._fatal)) @@ -478,7 +415,7 @@ class Scheduler: # ---- dispatch ---- - def _dispatch(self, request: Request, weight: float = 0.0) -> DispatchResult: + def _dispatch(self, request: Request) -> DispatchResult: # Explicit housekeeping commands are deterministic: they route straight # to the meta skill, bypassing the generic guards (which misread a # task-like skill name as the task). Natural-language phrasings still go @@ -508,9 +445,9 @@ class Scheduler: action_tau=self.action_tau, ) if isinstance(navigation, CreateCategory): - return self._dispatch_create_category(request, weight) + return self._dispatch_create_category(request) if isinstance(navigation, CreateSkill): - return self._dispatch_skill(request, navigation.category, weight) + return self._dispatch_skill(request, navigation.category) if navigation.category in CANNED_CATEGORIES: return self._run_skill(navigation, request) if navigation.category in HARD_LOCKED_CATEGORIES: @@ -530,12 +467,10 @@ class Scheduler: ) if self._category_locked(navigation.category): return self._blocked_create(request, navigation.category) - return self._dispatch_skill(request, navigation.category, weight) + return self._dispatch_skill(request, navigation.category) return self._run_skill(navigation, request) - def _dispatch_create_category( - self, request: Request, weight: float = 0.0 - ) -> DispatchResult: + def _dispatch_create_category(self, request: Request) -> DispatchResult: """Queue a new top-level category for the `llm` draft worker. The gate stays free: the small model authors the category in the @@ -543,7 +478,7 @@ class Scheduler: inside it and hands off to the codegen body worker. On failure the request is not re-dispatched and the user is told. """ - self._queue_draft(request, None, "category", weight) + self._queue_draft(request, None, "category") return DispatchResult( kind="create_category", summary=( @@ -553,7 +488,7 @@ class Scheduler: ) def _dispatch_skill( - self, request: Request, category: str, weight: float = 0.0 + self, request: Request, category: str ) -> DispatchResult: """Queue a new skill leaf for the `llm` draft worker. @@ -576,7 +511,7 @@ class Scheduler: ), skill=name, ) - self._queue_draft(request, category, "skill", weight) + self._queue_draft(request, category, "skill") return DispatchResult( kind="create_skill", summary=( @@ -685,7 +620,7 @@ class Scheduler: question=outcome.needs_input, pre_act=outcome.pre_act, ) - self.current = Process(request=request, skill=skill.name, weight=0.5) + self.current = Process(request=request, skill=skill.name) self.trace.append( "needs_input", request.id, skill=skill.name, question=outcome.needs_input ) @@ -708,7 +643,7 @@ class Scheduler: requeued = False if outcome.updated_request and request.reentries < self.max_reentries: child = _requeue(request, outcome.updated_request) - self.queue.push(child, 0.5) + self.queue.push(child) self.trace.append("requeued", request.id, text=outcome.updated_request) if self.on_request_requeued is not None: self.on_request_requeued(request.id, child.id) @@ -950,7 +885,7 @@ class Scheduler: offer.status = "awaiting_user" if chosen == "retry": retry = Request(offer.request_text, source="repair_retry") - self.queue.push(retry, 0.5) + self.queue.push(retry) with self._lock: offer.status = "done" self.trace.append("repair_retry", offer.run_id, skill=offer.skill) @@ -1017,7 +952,7 @@ class Scheduler: offer.status = "done" request = Request(offer.request_text, source="repair") self._start_skill_write( - request, offer.category, draft, 0.5, repair_evidence=offer.evidence + request, offer.category, draft, repair_evidence=offer.evidence ) self.trace.append( "repair_executed", @@ -1046,7 +981,6 @@ class Scheduler: request: Request, category: str | None, kind: str, - weight: float, approved: bool = False, ) -> None: """Queue a category or skill draft for the `llm` worker. @@ -1061,7 +995,6 @@ class Scheduler: DraftAuthor( request=request, category=category, - weight=weight, kind=kind, approved=approved, ) @@ -1135,7 +1068,7 @@ class Scheduler: category=draft.name, description=draft.description, ) - self._queue_draft(job.request, draft.name, "skill", job.weight, approved=True) + self._queue_draft(job.request, draft.name, "skill", approved=True) def _author_skill(self, job: DraftAuthor) -> None: """Author a skill leaf stub, then launch the codegen body write. @@ -1192,7 +1125,7 @@ class Scheduler: ) if self.codegen is None: return - self._start_skill_write(job.request, job.category, draft, job.weight) + self._start_skill_write(job.request, job.category, draft) def _fail_draft(self, job: DraftAuthor, exc: Exception) -> None: """Surface a failed draft authoring; the request is not re-dispatched.""" @@ -1314,7 +1247,6 @@ class Scheduler: request: Request, category: str, draft: SkillDraft, - weight: float, repair_evidence: dict | None = None, reason_kind: str = "run_failure", ) -> None: @@ -1355,7 +1287,6 @@ class Scheduler: request=request, category=category, draft=draft, - weight=weight, repair_evidence=repair_evidence, reason_kind=reason_kind, ) @@ -1860,12 +1791,11 @@ class Scheduler: requeued = job.request.copy_for_requeue() requeued.meta["awaiting_skill_body"] = [job.category, job.draft.name] requeued.meta["parent_run"] = job.request.id - self.queue.push(requeued, job.weight) + self.queue.push(requeued) self.trace.append( "skill_requeued", job.request.id, text=requeued.text, - weight=job.weight, ) print( f"[codegen] body ready for {job.category}.{job.draft.name}; " @@ -1953,7 +1883,7 @@ class Scheduler: if request_text else Request(f"write the body for {category}.{name}: {draft.description}", source="restart") ) - self._start_skill_write(origin, category, draft, 0.5) + self._start_skill_write(origin, category, draft) self.trace.append("skill_restarted", origin.id, category=category, skill=name) return "running", f"restarting body write for {category}.{name}" @@ -2092,7 +2022,6 @@ class Scheduler: origin, category, draft, - 0.5, repair_evidence=evidence, reason_kind="manual", ) @@ -2187,8 +2116,8 @@ class Scheduler: if offered: lines.append(f"repair offers: {len(offered)} (use `repairs`)") lines.append(f"queue: {len(self.queue)} pending") - for weight, request in self.queue.items(): - lines.append(f" {request.id} w={weight:.2f} {request.text[:60]}") + for request in self.queue.items(): + lines.append(f" {request.id} {request.text[:60]}") pending_timers = self.timers.pending() if pending_timers: lines.append(f"timers: {len(pending_timers)} scheduled") diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index dd8f6d1..5691aff 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -65,7 +65,7 @@ function shortPhase(phase) { return phase.replace("navigate:", "nav:"); } -const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "act"]; +const ALL_PHASES = ["navigate:category", "navigate:leaf", "act"]; function optionProbs(row) { return (row.options || []).map((o) => ({ @@ -130,9 +130,7 @@ function eventRow(evt) { div.textContent = `assessed → ${evt.success ? "ok" : "fail"}`; div.title = evt.summary || ""; } else if (evt.kind === "queued") { - div.textContent = `queued (${evt.label})`; - } else if (evt.kind === "preempted") { - div.textContent = `preempted ${evt.preempted}`; + div.textContent = "queued"; } else if (evt.kind === "skill_writing") { div.textContent = `writing skill ${evt.skill} — ${evt.description} (${evt.model || "codegen"})`; if (evt.contract_ref) { @@ -420,9 +418,7 @@ function eventNode(evt) { node.appendChild(req); } } else if (evt.kind === "queued") { - body.textContent = `urgency ${evt.label} (weight ${Number(evt.weight || 0).toFixed(2)})`; - } else if (evt.kind === "preempted") { - body.textContent = `interrupted ${evt.preempted}, requeued with state`; + body.textContent = "queued"; } else if (evt.kind === "dropped") { body.textContent = evt.reason || ""; } else if (evt.kind === "skill_writing") { @@ -825,7 +821,7 @@ function renderStatus() { q.className = "muted"; q.style.marginTop = "8px"; q.textContent = state.status.queue - .map((item) => `${item.id} w=${item.weight.toFixed(2)} ${item.text}`) + .map((item) => `${item.id} ${item.text}`) .join("\n") || "queue empty"; el.appendChild(q); diff --git a/semif_agent/static/style.css b/semif_agent/static/style.css index cb5ec0f..d8028e1 100644 --- a/semif_agent/static/style.css +++ b/semif_agent/static/style.css @@ -183,8 +183,6 @@ select { } .pill.gate { background: #2b3a52; color: #9ec1ff; } -.pill.choice { background: #4a3a2b; color: #ffd59e; } -.pill.score { background: #3a2b4a; color: #d59eff; } .pill.navigate { background: #2b4a3a; color: #9effd5; } .pill.act { background: #2b464a; color: #9eeaff; } .pill.assess { background: #4a2b2b; color: #ff9e9e; } diff --git a/semif_agent/trace.py b/semif_agent/trace.py index f4c34b9..b23da71 100644 --- a/semif_agent/trace.py +++ b/semif_agent/trace.py @@ -2,7 +2,7 @@ scheduler. Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events -(submit, dropped, queued, preempted, assessed, requeued, ...) live here in +(submit, dropped, queued, dequeued, assessed, requeued, ...) live here in `runs.jsonl`, keyed by `run_id` (the request id) so the dashboard can rebuild each run's flow without touching the decision-log contract. Both files are append-only; replays read them in order. diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 9ff3ab9..9da5bc5 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -111,7 +111,7 @@ def test_pipeline_end_to_end(tmp_path): for text in inputs: status, detail = scheduler.submit(text) print(f"[{status}] {detail}") - assert status in ("running", "preempted", "queued", "rejected") + assert status in ("running", "queued", "rejected") scheduler.run_queue() @@ -263,7 +263,7 @@ def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): ), ] queued: list = [] - scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + scheduler._queue_draft = lambda request, category, kind: queued.append( (category, kind) ) @@ -287,7 +287,7 @@ def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): assert read.skill == "next_message" -def test_busy_choice_path(tmp_path): +def test_busy_queue_path(tmp_path): config = load_config() require_real(config) _isolate_runtime(config, tmp_path) @@ -297,7 +297,7 @@ def test_busy_choice_path(tmp_path): scheduler.busy("driving on the freeway", skill="driving") status, detail = scheduler.submit("tell me if my package was delivered") print(f"[{status}] {detail}") - assert status in ("preempted", "queued") + assert status == "queued" scheduler.idle() @@ -442,7 +442,6 @@ def test_fidelity_gate_is_a_real_semif_decision(tmp_path): draft=SkillDraft( name="track_delivery", description="Check a package's delivery status." ), - weight=0.5, ) undeclared = '''\ from semif_agent.skills import ActionResult @@ -502,7 +501,7 @@ def test_create_skill_empty_category_does_not_wedge(tmp_path): for _ in range(2): status, detail = scheduler.submit("look up flights to japan for february") print(f"[{status}] {detail}") - assert status in ("running", "preempted", "queued", "rejected", "error") + assert status in ("running", "queued", "rejected", "error") assert scheduler.current is None, "scheduler must never stay wedged after a submit" status, detail = scheduler.submit("tell me if my package was delivered") @@ -536,7 +535,7 @@ def test_create_simplex_send_skill(tmp_path): status, detail = scheduler.submit("send a simplex message to pepper saying hi") print(f"[{status}] {detail}") - assert status in ("running", "preempted", "queued", "rejected") + assert status in ("running", "queued", "rejected") assert "new skill for simplex" in detail, ( "a send request must route to create_skill for simplex" ) diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 52ae7da..e4289f5 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -225,7 +225,7 @@ def test_service_drain_routes_queued_run_to_owner(tmp_path): scheduler = build_scheduler(tmp_path) service = build_service(scheduler) request = Request("queued work", source="simplex:4") - scheduler.queue.push(request, 0.5) + scheduler.queue.push(request) service._owners[request.id] = ("simplex", "4") service.drain() @@ -296,15 +296,15 @@ def test_result_detail_unwraps_scheduler_summary(): from semif_agent.gateway.service import _result_detail assert _result_detail("time.now: ok — 2026-10-06 12:00") == "2026-10-06 12:00" - assert _result_detail("interrupted x; time.now: ok — 12:00") == "12:00" + assert _result_detail("time.now: failed — boom") == "boom" assert _result_detail("a plain reply") == "a plain reply" def test_result_only_speaks_detail_and_drops_status(tmp_path): scheduler = build_scheduler(tmp_path) service = build_result_only_service(scheduler) - service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result") - service._reply("voice", "c", "urgency low (weight 0.20)", kind="status") + service._reply("voice", "c", "time.now: ok — 12:00", kind="result") + service._reply("voice", "c", "queued", kind="status") service._reply("voice", "c", "Which account?", kind="question") assert drain_outbound(service) == ["12:00", "Which account?"] @@ -312,11 +312,11 @@ def test_result_only_speaks_detail_and_drops_status(tmp_path): def test_plain_adapter_keeps_full_scheduler_output(tmp_path): scheduler = build_scheduler(tmp_path) service = build_service(scheduler) # FakeAdapter (simplex), not result_only - service._reply("simplex", "4", "[high] time.now: ok — 12:00", kind="result") - service._reply("simplex", "4", "urgency low (weight 0.20)", kind="status") + service._reply("simplex", "4", "time.now: ok — 12:00", kind="result") + service._reply("simplex", "4", "queued", kind="status") assert drain_outbound(service) == [ - "[high] time.now: ok — 12:00", - "urgency low (weight 0.20)", + "time.now: ok — 12:00", + "queued", ] @@ -325,9 +325,9 @@ def test_config_can_turn_result_only_off(tmp_path): service = build_result_only_service( scheduler, config={"voice": {"result_only": False}} ) - service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result") - service._reply("voice", "c", "urgency low", kind="status") - assert drain_outbound(service) == ["[high] time.now: ok — 12:00", "urgency low"] + service._reply("voice", "c", "time.now: ok — 12:00", kind="result") + service._reply("voice", "c", "queued", kind="status") + assert drain_outbound(service) == ["time.now: ok — 12:00", "queued"] # ---- LXMF adapter ---- diff --git a/tests/test_housekeeping.py b/tests/test_housekeeping.py index a0477ce..da1ef1d 100644 --- a/tests/test_housekeeping.py +++ b/tests/test_housekeeping.py @@ -346,7 +346,7 @@ def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch): _add_skill(scheduler, "calendar", "foo") captured = {} - def fake_start(request, category, draft, weight, repair_evidence=None, reason_kind="run_failure"): + def fake_start(request, category, draft, repair_evidence=None, reason_kind="run_failure"): captured.update( category=category, repair_evidence=repair_evidence, @@ -371,7 +371,7 @@ def test_regen_skill_stub_has_no_evidence(tmp_path, monkeypatch): ] captured = {} - def fake_start(request, category, draft, weight, repair_evidence=None, reason_kind="run_failure"): + def fake_start(request, category, draft, repair_evidence=None, reason_kind="run_failure"): captured.update(repair_evidence=repair_evidence, reason_kind=reason_kind) monkeypatch.setattr(scheduler, "_start_skill_write", fake_start) @@ -389,7 +389,6 @@ def test_cancel_skill_build_discards_and_deletes(tmp_path): request=Request("build foo"), category="calendar", draft=SkillDraft(name="foo", description="d"), - weight=0.5, ) ) @@ -411,7 +410,6 @@ def test_consume_cancelled_discards_queued_write(tmp_path): request=Request("build foo"), category="calendar", draft=SkillDraft(name="foo", description="d"), - weight=0.5, ) scheduler._cancelled.add(("calendar", "foo")) assert scheduler._consume_cancelled(job) is True diff --git a/tests/test_humanize.py b/tests/test_humanize.py index 55653e8..b3564b6 100644 --- a/tests/test_humanize.py +++ b/tests/test_humanize.py @@ -98,12 +98,12 @@ def build_service(llm, config): def test_gateway_humanizes_only_result_lines(): llm = FakeClient(reply="It is 12:00.") service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}}) - service._reply("simplex", "c", "[high] time.now: ok — 12:00", kind="result") - service._reply("simplex", "c", "urgency low (weight 0.20)", kind="status") + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + service._reply("simplex", "c", "queued", kind="status") service._reply("simplex", "c", "Which account?", kind="question") assert [service.outbound["simplex"].get_nowait().text for _ in range(3)] == [ "It is 12:00.", - "urgency low (weight 0.20)", + "queued", "Which account?", ] @@ -111,8 +111,8 @@ def test_gateway_humanizes_only_result_lines(): def test_gateway_humanize_off_by_default(): llm = FakeClient(reply="should not be used") service = build_service(llm, {"simplex": {}}) - service._reply("simplex", "c", "[high] time.now: ok — 12:00", kind="result") - assert service.outbound["simplex"].get_nowait().text == "[high] time.now: ok — 12:00" + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00" assert llm.calls == [] diff --git a/tests/test_queue.py b/tests/test_queue.py index 149024f..fdb36a3 100644 --- a/tests/test_queue.py +++ b/tests/test_queue.py @@ -1,74 +1,39 @@ -import pytest - -from semif_agent.queue import UrgencyQueue +from semif_agent.queue import RequestQueue from semif_agent.decisions import Request -def make(text, weight): - return Request(text=text), weight +def make(text): + return Request(text=text) -def test_order_by_weight_desc(): - q = UrgencyQueue() - req_a, _ = make("low", 0.25) - req_c, _ = make("critical", 1.0) - req_h, _ = make("high", 0.75) - q.push(req_a, 0.25) - q.push(req_c, 1.0) - q.push(req_h, 0.75) - assert q.pop().text == "critical" - assert q.pop().text == "high" - assert q.pop().text == "low" +def test_fifo_order(): + q = RequestQueue() + q.push(make("first")) + q.push(make("second")) + q.push(make("third")) + assert q.pop().text == "first" + assert q.pop().text == "second" + assert q.pop().text == "third" assert q.pop() is None -def test_fifo_tiebreak(): - q = UrgencyQueue() - req_a, _ = make("first", 0.5) - req_b, _ = make("second", 0.5) - q.push(req_a, 0.5) - q.push(req_b, 0.5) - assert q.pop().text == "first" - assert q.pop().text == "second" - - -def test_fifo_beats_recency(): - q = UrgencyQueue() - old, _ = make("older", 0.5) - new, _ = make("newer", 0.5) - q.push(old, 0.5, recency=1.0) - q.push(new, 0.5, recency=2.0) - assert q.pop().text == "older" - - def test_peek_does_not_remove(): - q = UrgencyQueue() - req, _ = make("peek", 0.9) - q.push(req, 0.9) + q = RequestQueue() + q.push(make("peek")) assert q.peek().text == "peek" assert len(q) == 1 def test_bounds_reject(): - q = UrgencyQueue(max_size=2) - assert q.push(make("a", 1.0)[0], 1.0) - assert q.push(make("b", 1.0)[0], 1.0) - assert not q.push(make("c", 1.0)[0], 1.0) + q = RequestQueue(max_size=2) + assert q.push(make("a")) + assert q.push(make("b")) + assert not q.push(make("c")) -def test_age_raises_priority(): - q = UrgencyQueue(age_rate=1.0) - old, _ = make("aging", 0.2) - new, _ = make("busy", 1.0) - q.push(old, 0.2) - q.push(new, 1.0) - q.age(dt=10.0) - assert q.peek().text == "aging" - - -def test_items_sorted(): - q = UrgencyQueue() - q.push(make("b", 0.5)[0], 0.5) - q.push(make("a", 1.0)[0], 1.0) - weights = [weight for weight, _ in q.items()] - assert weights == [1.0, 0.5] \ No newline at end of file +def test_items_in_arrival_order(): + q = RequestQueue() + q.push(make("b")) + q.push(make("a")) + texts = [request.text for request in q.items()] + assert texts == ["b", "a"] diff --git a/tests/test_skills.py b/tests/test_skills.py index 25a2762..d80cebb 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -1022,7 +1022,7 @@ def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path): ] } queued: list = [] - scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + scheduler._queue_draft = lambda request, category, kind: queued.append( (category, kind) ) return scheduler, queued @@ -1071,7 +1071,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path): Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), ] queued: list = [] - scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + scheduler._queue_draft = lambda request, category, kind: queued.append( (category, kind) ) request = Request("send a simplex message to pepper") @@ -1154,7 +1154,7 @@ def test_creation_approval_off_proceeds(tmp_path): returns immediately and posts nothing.""" scheduler = _scheduler(tmp_path) job = DraftAuthor( - request=Request("book a trip"), category=None, weight=0.5, kind="category" + request=Request("book a trip"), category=None, kind="category" ) assert scheduler._request_approval(job, "category", "travel", "Trips.") is True assert scheduler.pending_approvals() == [] @@ -1165,7 +1165,7 @@ def test_creation_approval_approved_proceeds(tmp_path): scheduler.creation_approval = True scheduler.defer_questions = True job = DraftAuthor( - request=Request("book a trip"), category=None, weight=0.5, kind="category" + request=Request("book a trip"), category=None, kind="category" ) result = {} thread = threading.Thread( @@ -1188,7 +1188,7 @@ def test_creation_approval_denied_aborts(tmp_path): scheduler.creation_approval = True scheduler.defer_questions = True job = DraftAuthor( - request=Request("book a trip"), category="travel", weight=0.5, kind="skill" + request=Request("book a trip"), category="travel", kind="skill" ) result = {} thread = threading.Thread( @@ -1211,7 +1211,7 @@ def test_creation_approval_timeout_denies(tmp_path): scheduler.defer_questions = True scheduler.elicitation_wait = 0.1 job = DraftAuthor( - request=Request("book a trip"), category="travel", weight=0.5, kind="skill" + request=Request("book a trip"), category="travel", kind="skill" ) assert scheduler._request_approval(job, "skill", "book_flight", "Book.") is False assert any( @@ -1226,7 +1226,7 @@ def test_creation_approval_without_front_end_denies(tmp_path): scheduler.creation_approval = True scheduler.defer_questions = False job = DraftAuthor( - request=Request("book a trip"), category="travel", weight=0.5, kind="skill" + request=Request("book a trip"), category="travel", kind="skill" ) assert scheduler._request_approval(job, "skill", "book_flight", "Book.") is False assert any( @@ -1242,7 +1242,6 @@ def test_creation_approval_chain_skips_second_prompt(tmp_path): job = DraftAuthor( request=Request("book a trip"), category="travel", - weight=0.5, kind="skill", approved=True, ) @@ -1261,7 +1260,7 @@ def test_author_category_denied_does_not_register(tmp_path, monkeypatch): lambda client, request, tree: CategoryDraft(name="travel", description="Trips."), ) job = DraftAuthor( - request=Request("book a trip"), category=None, weight=0.5, kind="category" + request=Request("book a trip"), category=None, kind="category" ) thread = threading.Thread(target=scheduler._author_category, args=(job,)) thread.start() @@ -1283,7 +1282,7 @@ def test_author_skill_denied_does_not_register(tmp_path, monkeypatch): ), ) job = DraftAuthor( - request=Request("book a flight"), category="travel", weight=0.5, kind="skill" + request=Request("book a flight"), category="travel", kind="skill" ) thread = threading.Thread(target=scheduler._author_skill, args=(job,)) thread.start() @@ -1334,7 +1333,7 @@ def test_dispatch_skill_awaiting_body_does_not_reauthor(tmp_path): scheduler = _scheduler(tmp_path) request = Request("track my package") request.meta["awaiting_skill_body"] = ["tracking", "track_live"] - result = scheduler._dispatch_skill(request, "tracking", 0.5) + result = scheduler._dispatch_skill(request, "tracking") assert result.kind == "create_skill" assert "track_live" in result.summary assert "restart" in result.summary @@ -1369,7 +1368,7 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path): leaf = scheduler.tree["tracking"][0] request = Request("track my drone delivery in real time") - scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5) + scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package.")) assert leaf.writing is True deadline = time.monotonic() + 10 @@ -1420,7 +1419,7 @@ def test_async_skill_write_fails_gracefully_on_bad_contract(tmp_path): leaf = scheduler.tree["tracking"][0] request = Request("track my drone delivery in real time") - scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5) + scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package.")) deadline = time.monotonic() + 10 failed = None @@ -1470,7 +1469,7 @@ def test_async_skill_write_fails_gracefully_on_unimported_names(tmp_path): request = Request("track my drone delivery in real time") scheduler._start_skill_write( - request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5 + request, "tracking", SkillDraft(name="track_live", description="Follow a package.") ) deadline = time.monotonic() + 10 @@ -1642,7 +1641,7 @@ def test_deferred_elicitation_asks_and_records(tmp_path): scheduler.elicitation_enabled = True request = Request("track my package") draft = SkillDraft(name="track_live", description="Follow a package.") - job = SkillWrite(request=request, category="tracking", draft=draft, weight=0.5) + job = SkillWrite(request=request, category="tracking", draft=draft) def answerer() -> None: deadline = time.monotonic() + 5 @@ -1680,7 +1679,7 @@ def test_async_skill_write_regen_ladder_on_failing_test(tmp_path): request = Request("track my drone delivery in real time") scheduler._start_skill_write( - request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5 + request, "tracking", SkillDraft(name="track_live", description="Follow a package.") ) deadline = time.monotonic() + 10 @@ -1751,7 +1750,6 @@ def test_post_questions_asks_one_at_a_time(tmp_path): request=Request("track it"), category="tracking", draft=SkillDraft(name="probe", description="Probe."), - weight=0.5, ) result: dict = {} thread = threading.Thread( @@ -1790,7 +1788,6 @@ def test_post_questions_timeout_drops_remaining(tmp_path): request=Request("track it"), category="tracking", draft=SkillDraft(name="probe", description="Probe."), - weight=0.5, ) result: dict = {} thread = threading.Thread( @@ -1818,7 +1815,6 @@ def test_post_questions_times_out(tmp_path): request=Request("track it"), category="tracking", draft=SkillDraft(name="probe", description="Probe."), - weight=0.5, ) assert scheduler._post_questions(job, ["Q?"]) == {} assert scheduler.pending_questions() == []