codegen: fidelity gate reads the whole body; bound artifacts to engine ctx
The fidelity gate truncated the body to 4000 chars, so a body whose real
action sat after its helpers (the common shape) was judged on a prefix with
no action and wrongly returned `reconsider` -- a false reject that wasted a
rewrite and mislabeled a working skill. Live-engine probe: the truncated
state scored reconsider 0.96; the whole body scores accept 0.98.
- Fidelity gate: feed the whole body plus a deterministic operation
inventory and the de-identified goal; drop the raw request from the state
(a remote-engine PII path that added no signal). Ask the positive question
("is there a concrete operation that realizes the goal?") and give the gate
its own `codegen.fidelity.tau` instead of the run-assessment tau.
- Artifact size budget: a decision ingests a generated artifact whole, so
bound it. `parse_skill_body`/`parse_skill_test` reject an over-budget
artifact (`ArtifactTooLong`); the codegen retry ladder asks for a shorter
one. The ceiling derives from the active engine's context
(`DecisionEngine.context_tokens`: `engine.context_tokens` for the local
GGUF, `engine.winnow.context_tokens` for Winnow) minus
`codegen.decision_reserve_tokens`; `codegen.max_body_tokens` /
`max_test_tokens` override (separate limits).
- `codegen.operation_inventory()`: static HTTP-verb/path, CLI, mail, file,
and timer inventory, resolving the verb at the call site so a thin-helper
body's real endpoint is visible.
- Docs: AGENTS.md, README.md, CODEGEN.md, config.example.json.
- Tests: unit coverage for the budget, inventory, retry-shortening, and the
gate state; integration regression `test_fidelity_gate_reads_the_whole_body`
(real engine) guards the truncation bug.
This commit is contained in:
1 parent
1833932f1c
commit
9757ae893e
12 files changed
+526
-52
No files matched your search
@@ -541,9 +541,10 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
codegen. Bodies
|
codegen. Bodies
|
||||||
must perform the real action via stdlib transports with values from
|
must perform the real action via stdlib transports with values from
|
||||||
`ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a
|
`ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a
|
||||||
fidelity gate (`authoring:fidelity`, a SemIf accept/reconsider decision) plus
|
fidelity gate (`authoring:fidelity`, a SemIf accept/reconsider decision over
|
||||||
static declaration checks regenerates a simulated body once with the
|
the whole body + an operation inventory) plus static declaration checks
|
||||||
de-identified evidence bundle, then accepts it badged `unverified`. A failed real run logs a
|
regenerates a simulated body once with the de-identified evidence bundle, then
|
||||||
|
accepts it traced (never a hard authoring failure). A failed real run logs a
|
||||||
SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in
|
SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in
|
||||||
REPL/dashboard; repair writes carry a de-identified evidence bundle (a generic
|
REPL/dashboard; repair writes carry a de-identified evidence bundle (a generic
|
||||||
failure kind, the integration, the goal, and the previous body — never the run's
|
failure kind, the integration, the goal, and the previous body — never the run's
|
||||||
@@ -686,8 +687,11 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
decision log and `dream` cost are unchanged because `DecisionResult` is the
|
decision log and `dream` cost are unchanged because `DecisionResult` is the
|
||||||
same contract.
|
same contract.
|
||||||
- Context differs by provider (the local engine's `engine.context_tokens` vs the
|
- Context differs by provider (the local engine's `engine.context_tokens` vs the
|
||||||
remote server's own `--ctx-size`); a state that overflows is a fatal
|
remote server's own `--ctx-size`, mirrored in `engine.winnow.context_tokens`);
|
||||||
`EngineUnavailable`, the same class as the local token limit.
|
a state that overflows is a fatal `EngineUnavailable`, the same class as the
|
||||||
|
local token limit. Every engine exposes its window as `context_tokens` (a
|
||||||
|
`DecisionEngine` property), which the scheduler uses to size generated
|
||||||
|
artifacts — see "Artifact size budget".
|
||||||
|
|
||||||
### Environment
|
### Environment
|
||||||
- The core is pure stdlib and runs anywhere Python does. Never pip-install heavy
|
- The core is pure stdlib and runs anywhere Python does. Never pip-install heavy
|
||||||
@@ -972,11 +976,15 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
name the body references must be imported/bound — both enforced by
|
name the body references must be imported/bound — both enforced by
|
||||||
`parse_skill_body`).
|
`parse_skill_body`).
|
||||||
2. **fidelity gate** (`authoring:fidelity` SemIf decision +
|
2. **fidelity gate** (`authoring:fidelity` SemIf decision +
|
||||||
`integration_findings`): a rapid sanity check (accept/reconsider) — is the
|
`integration_findings`): a rapid sanity check (accept/reconsider) — does
|
||||||
action real or simulated/declared-but-unused? It only triggers a rewrite,
|
the body contain a concrete, side-effecting operation that really performs
|
||||||
never a diagnosis. One corrective regen with the de-identified evidence bundle
|
its goal (vs simulated/declared-but-unused)? The state carries the
|
||||||
(`codegen.fidelity.max_attempts`), then accept with a trace rather than
|
**whole** body plus a deterministic operation inventory and the
|
||||||
hard-failing authoring.
|
de-identified goal (never the raw request), and asks the positive question;
|
||||||
|
its threshold is its own `codegen.fidelity.tau`. It only triggers a
|
||||||
|
rewrite, never a diagnosis. One corrective regen with the de-identified
|
||||||
|
evidence bundle (`codegen.fidelity.max_attempts`, inventory + findings
|
||||||
|
included), then accept with a trace rather than hard-failing authoring.
|
||||||
3. **contract** (`parse_contract`): read from the body's own flat `CONTRACT`
|
3. **contract** (`parse_contract`): read from the body's own flat `CONTRACT`
|
||||||
constant — a single flat object of snake_case variable name -> semantic
|
constant — a single flat object of snake_case variable name -> semantic
|
||||||
description, for user input and SemIf only (no types/validation; that lives
|
description, for user input and SemIf only (no types/validation; that lives
|
||||||
@@ -1043,17 +1051,39 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
service/transport carries what the questions used to; the only remaining
|
service/transport carries what the questions used to; the only remaining
|
||||||
question queue is the repair `ask_user` path (local).
|
question queue is the repair `ask_user` path (local).
|
||||||
- **Fidelity gate.** After the body lands, `authoring:fidelity` — a real SemIf
|
- **Fidelity gate.** After the body lands, `authoring:fidelity` — a real SemIf
|
||||||
accept/reconsider decision (`P(reconsider) >= tau` or any static
|
accept/reconsider decision (`P(reconsider) >= codegen.fidelity.tau` or any
|
||||||
`integration_findings` from the declared transport vs. real calls and declared
|
static `integration_findings` from the declared transport vs. real calls and
|
||||||
config_vars actually read) decides whether the body really performs the
|
declared config_vars actually read) decides whether the body really performs
|
||||||
action. The gate never diagnoses: it only triggers a rewrite, which is handed
|
the action. **The state carries the whole body, never a prefix**, plus a
|
||||||
the de-identified evidence bundle as-is (goal, description, raw
|
deterministic `operation_inventory` (the HTTP verb + path, CLI, mail, file
|
||||||
INTEGRATION, findings, SemIf verdict+probs, previous body — no request). A
|
write, or timer it performs) and the de-identified goal; the raw request is
|
||||||
rejected body is
|
**not** included (it added a remote-engine PII path and no signal — the goal
|
||||||
rewritten once (`codegen.fidelity.max_attempts`, reason_kind `fidelity`); a
|
is the reusable action). The question is positive ("is there a concrete
|
||||||
body that still fails is accepted (never hard-fail authoring) but traced
|
operation that realizes the goal?"), which the model answers far more
|
||||||
(`fidelity_review`, `performs_real_action=false`) and badged `unverified` in
|
reliably than the old "does it simulate?" on a prefix. It never diagnoses: it
|
||||||
the dashboard. A decision row is logged under phase `authoring:fidelity`.
|
only triggers a rewrite, which is handed the de-identified evidence bundle
|
||||||
|
as-is (goal, description, raw INTEGRATION, findings, operation inventory,
|
||||||
|
SemIf verdict+probs, previous body). A rejected body is rewritten once
|
||||||
|
(`codegen.fidelity.max_attempts`, reason_kind `fidelity`); a body that still
|
||||||
|
fails is accepted (never hard-fail authoring) but traced (`fidelity_review`,
|
||||||
|
`performs_real_action=false`). A decision row is logged under phase
|
||||||
|
`authoring:fidelity`. (An *undeclared* INTEGRATION is what the dashboard
|
||||||
|
badges `unverified` — that is `integration_source`, not the fidelity verdict.)
|
||||||
|
- **Artifact size budget.** A decision ingests a generated artifact *whole*, so
|
||||||
|
each is bounded: `parse_skill_body`/`parse_skill_test` reject an over-budget
|
||||||
|
artifact with `ArtifactTooLong` (a hard ceiling, since it is a hard limit),
|
||||||
|
which the codegen retry ladder answers with a shorter-artifact prompt. The
|
||||||
|
ceiling is derived from the **active engine's context** —
|
||||||
|
`engine.context_tokens` (local GGUF) or `engine.winnow.context_tokens`
|
||||||
|
(Winnow; must mirror the server's `--ctx-size`) — minus
|
||||||
|
`codegen.decision_reserve_tokens` (default 1024), the headroom for everything
|
||||||
|
else in the fidelity state (goal, description, integration, findings,
|
||||||
|
inventory, question, options, prefill margin), which is known because codegen
|
||||||
|
runs immediately before the gate. `codegen.max_body_tokens` /
|
||||||
|
`max_test_tokens` (0 = derive; a positive value overrides — lower it to avoid
|
||||||
|
a long fidelity evaluation) set each artifact's budget, converted to chars by
|
||||||
|
`chars_per_token`. This is why the gate never truncates and a body can never
|
||||||
|
exceed what the gate can read.
|
||||||
- **Repair loop.** A failed real run (assessment failure or a raised skill
|
- **Repair loop.** A failed real run (assessment failure or a raised skill
|
||||||
error) logs a SemIf choice (phase `repair:choice`) offering
|
error) logs a SemIf choice (phase `repair:choice`) offering
|
||||||
`retry` / `repair_skill` / `ask_user` / `no_repair`, recorded as a
|
`retry` / `repair_skill` / `ask_user` / `no_repair`, recorded as a
|
||||||
|
|||||||
@@ -550,6 +550,12 @@ therefore run as a later step of a chain.
|
|||||||
see how `nextcloud.create_event` caches the extracted title/description and the
|
see how `nextcloud.create_event` caches the extracted title/description and the
|
||||||
answers it collected.
|
answers it collected.
|
||||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
||||||
|
- **Keep the body small — it is ingested whole.** The fidelity decision reads
|
||||||
|
the *entire* body, so a body that exceeds the engine's context budget is
|
||||||
|
rejected outright (the pipeline retries once with a "make it shorter"
|
||||||
|
instruction). Delegate protocol details to a bridge instead of hand-rolling a
|
||||||
|
client, and keep `act` to one purpose; a long body is a signal that the
|
||||||
|
integration belongs in a bridge.
|
||||||
- **The function is `act` exactly.** The module is imported under its registered
|
- **The function is `act` exactly.** The module is imported under its registered
|
||||||
leaf name; the entry point is a module-level `act(ctx, request)`.
|
leaf name; the entry point is a module-level `act(ctx, request)`.
|
||||||
|
|
||||||
@@ -651,6 +657,9 @@ A generated skill is accepted only if:
|
|||||||
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
|
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
|
||||||
service's native protocol), resolves recipients with a SemIf sub-decision,
|
service's native protocol), resolves recipients with a SemIf sub-decision,
|
||||||
and sends only on explicit user intent.
|
and sends only on explicit user intent.
|
||||||
|
14. It is small enough to be ingested whole by the fidelity decision (a body
|
||||||
|
over the engine's artifact budget is rejected as too long) — delegate
|
||||||
|
protocol details to a bridge rather than hand-rolling them.
|
||||||
|
|
||||||
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
|
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
|
||||||
body outright. The rest are not statically rejected: a missing or inconsistent
|
body outright. The rest are not statically rejected: a missing or inconsistent
|
||||||
|
|||||||
@@ -191,9 +191,15 @@ worker. It is **asynchronous**, so the gate stays free while either model thinks
|
|||||||
codegen is the primarily-cloud model, so it receives only the de-identified
|
codegen is the primarily-cloud model, so it receives only the de-identified
|
||||||
spec — never the user's request, question answers, or run output.
|
spec — never the user's request, question answers, or run output.
|
||||||
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
|
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
|
||||||
static `integration_findings`): is the action real, or simulated? One
|
static `integration_findings`): does the body contain a concrete,
|
||||||
corrective regen with the de-identified evidence bundle, then accept-with-badge
|
side-effecting operation that really performs its goal? The state carries the
|
||||||
(`unverified`) rather than hard-fail.
|
**whole** body (never a prefix) plus a deterministic operation inventory and
|
||||||
|
the de-identified goal — never the raw request — and asks the positive
|
||||||
|
question rather than asking the model to prove a negative. Because a decision
|
||||||
|
ingests the body whole, generated artifacts are size-bounded
|
||||||
|
(`max_body_chars`/`max_test_chars`, derived from the engine's context). One
|
||||||
|
corrective regen with the de-identified evidence bundle (inventory + findings
|
||||||
|
included), then accept with a trace rather than hard-fail.
|
||||||
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
|
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
|
||||||
constant — a flat map of snake_case variable name → semantic description, for
|
constant — a flat map of snake_case variable name → semantic description, for
|
||||||
user input and SemIf only; `contract.json` is a persisted mirror.
|
user input and SemIf only; `contract.json` is a persisted mirror.
|
||||||
@@ -211,9 +217,9 @@ onto the new leaf. On failure the leaf stays a restartable stub. A whole new
|
|||||||
category runs the same chain deterministically:
|
category runs the same chain deterministically:
|
||||||
`create_category` → `create_skill` → async body → re-dispatch.
|
`create_category` → `create_skill` → async body → re-dispatch.
|
||||||
|
|
||||||
A rejected/simulated body is traced (`fidelity_review`), badged `unverified`,
|
A rejected/simulated body is traced (`fidelity_review`) and never blocks
|
||||||
and never blocks authoring. Codegen failures (including timeouts) surface as a
|
authoring. Codegen failures (including timeouts) surface as a graceful stub and
|
||||||
graceful stub and are retryable with `restart <category> <skill>`.
|
are retryable with `restart <category> <skill>`.
|
||||||
|
|
||||||
### What each model sees
|
### What each model sees
|
||||||
|
|
||||||
@@ -245,7 +251,7 @@ receives the user's request, question answers, or run output.
|
|||||||
| `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
|
| `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
|
||||||
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
|
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
|
||||||
| `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` |
|
| `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` |
|
||||||
| `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` |
|
| `authoring:fidelity` | `scheduler.py:1836` | skill, goal, description, `INTEGRATION` JSON, static findings, operation inventory, **whole** body (no raw request) | `accept` / `reconsider` |
|
||||||
| `repair:choice` | `scheduler.py:658` | skill, request, integration, truncated failure | `retry` / `repair_skill` / `ask_user` / `no_repair` |
|
| `repair:choice` | `scheduler.py:658` | skill, request, integration, truncated failure | `retry` / `repair_skill` / `ask_user` / `no_repair` |
|
||||||
| degeneration watchdog¹ | `cli.py:128` | `[codegen <model>]` + last 2000 chars of the stream | `continue` / `stop` |
|
| degeneration watchdog¹ | `cli.py:128` | `[codegen <model>]` + last 2000 chars of the stream | `continue` / `stop` |
|
||||||
| `codegen_regen`¹ | `cli.py:165` | `[testgen <model>]` + last 1200 chars of the test error | `regen_code` / `regen_test` / `regen_contract` |
|
| `codegen_regen`¹ | `cli.py:165` | `[testgen <model>]` + last 1200 chars of the test error | `regen_code` / `regen_test` / `regen_contract` |
|
||||||
|
|||||||
+9
-3
@@ -38,9 +38,10 @@
|
|||||||
"gpu_device": null,
|
"gpu_device": null,
|
||||||
"gpu_split": 0,
|
"gpu_split": 0,
|
||||||
"winnow": {
|
"winnow": {
|
||||||
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
|
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). context_tokens must mirror the server's --ctx-size: generated skill bodies are sized from the active engine's context so a fidelity decision can always ingest one whole. timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
|
||||||
"base_url": "http://127.0.0.1:8091",
|
"base_url": "http://127.0.0.1:8091",
|
||||||
"model": "",
|
"model": "",
|
||||||
|
"context_tokens": 32768,
|
||||||
"api_key": "",
|
"api_key": "",
|
||||||
"api_key_env": "",
|
"api_key_env": "",
|
||||||
"timeout": 120,
|
"timeout": 120,
|
||||||
@@ -102,9 +103,10 @@
|
|||||||
"wait_timeout": 900
|
"wait_timeout": 900
|
||||||
},
|
},
|
||||||
"fidelity": {
|
"fidelity": {
|
||||||
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle, bounded by max_attempts; a still-fake body is accepted but traced/badged, never a hard authoring failure.",
|
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). The state carries the WHOLE body (never a prefix) plus a deterministic operation inventory and the de-identified goal, and asks the positive question (is there a concrete operation that realizes the goal?). tau is this gate's own threshold, separate from the top-level tau. Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle (inventory + findings included), bounded by max_attempts; a still-fake body is accepted but traced, never a hard authoring failure.",
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"max_attempts": 1
|
"max_attempts": 1,
|
||||||
|
"tau": 0.6
|
||||||
},
|
},
|
||||||
"repair": {
|
"repair": {
|
||||||
"_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.",
|
"_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.",
|
||||||
@@ -113,6 +115,10 @@
|
|||||||
},
|
},
|
||||||
"test_timeout": 30,
|
"test_timeout": 30,
|
||||||
"test_max_attempts": 3,
|
"test_max_attempts": 3,
|
||||||
|
"_artifact_budget_comment": "Generated artifacts are ingested WHOLE by a decision (the fidelity gate reads the entire skill body), so each is size-bounded. max_body_tokens/max_test_tokens are hard ceilings; 0 derives each from the ACTIVE decision engine's context (engine.context_tokens for the local GGUF, engine.winnow.context_tokens for Winnow) minus decision_reserve_tokens — the headroom for everything else in the fidelity state (goal, description, integration, findings, operation inventory, question, options, engine prefill margin). A positive value overrides the derivation: lower it if you don't want to wait on a long fidelity evaluation, raise it if your engine has a larger window. chars_per_token above converts the token budget to the char limit the parser enforces; a body over budget is rejected (ArtifactTooLong) and the codegen retry ladder asks for a shorter one.",
|
||||||
|
"max_body_tokens": 0,
|
||||||
|
"max_test_tokens": 0,
|
||||||
|
"decision_reserve_tokens": 1024,
|
||||||
"contract_search": {
|
"contract_search": {
|
||||||
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
|
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
|
||||||
"enabled": true
|
"enabled": true
|
||||||
|
|||||||
@@ -220,6 +220,7 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
|
|||||||
WinnowConfig(
|
WinnowConfig(
|
||||||
base_url=endpoint["base_url"],
|
base_url=endpoint["base_url"],
|
||||||
model=_required_model(win, "engine.winnow"),
|
model=_required_model(win, "engine.winnow"),
|
||||||
|
context_tokens=int(win.get("context_tokens", 32768)),
|
||||||
timeout=float(win.get("timeout", 120.0)),
|
timeout=float(win.get("timeout", 120.0)),
|
||||||
retries=int(win.get("retries", 0)),
|
retries=int(win.get("retries", 0)),
|
||||||
api_key=endpoint["api_key"],
|
api_key=endpoint["api_key"],
|
||||||
|
|||||||
+125
-8
@@ -40,6 +40,18 @@ class DegenerationError(CodegenError):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ArtifactTooLong(ValueError):
|
||||||
|
"""A generated artifact exceeded the size budget for a decision.
|
||||||
|
|
||||||
|
A hard ceiling, not a warning: the artifact is ingested *whole* by a
|
||||||
|
decision (the fidelity gate reads the entire skill body), so it must fit
|
||||||
|
the decision engine's context with headroom for everything else in the
|
||||||
|
state. The budget is derived from the active engine's context; the codegen
|
||||||
|
retry ladder asks the model for a shorter artifact, and a body that still
|
||||||
|
cannot fit stubs out rather than shipping something the gate cannot read.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def read_skill_contract(path: str | None = None) -> str:
|
def read_skill_contract(path: str | None = None) -> str:
|
||||||
contract = Path(path) if path else DEFAULT_CONTRACT
|
contract = Path(path) if path else DEFAULT_CONTRACT
|
||||||
if not contract.is_file():
|
if not contract.is_file():
|
||||||
@@ -136,6 +148,9 @@ BODY_DIRECTIVES = (
|
|||||||
"employ a `ctx.engine` SemIf sub-decision over them and return the "
|
"employ a `ctx.engine` SemIf sub-decision over them and return the "
|
||||||
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
|
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
|
||||||
"send only when the reusable goal calls for it.\n"
|
"send only when the reusable goal calls for it.\n"
|
||||||
|
"Keep the body small: it is ingested whole by the decision engine's "
|
||||||
|
"fidelity check, so delegate protocol details to a bridge instead of "
|
||||||
|
"hand-rolling them, and keep `act` to one purpose.\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -256,13 +271,17 @@ def _unresolved_names(code: str) -> list[str]:
|
|||||||
return sorted(unresolved)
|
return sorted(unresolved)
|
||||||
|
|
||||||
|
|
||||||
def parse_skill_body(raw: str) -> str:
|
def parse_skill_body(raw: str, max_chars: int | None = None) -> str:
|
||||||
"""Extract and validate a Python skill body from the model's reply.
|
"""Extract and validate a Python skill body from the model's reply.
|
||||||
|
|
||||||
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
|
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
|
||||||
must parse, define a module-level `act` function, declare a valid flat
|
must parse, define a module-level `act` function, declare a valid flat
|
||||||
`CONTRACT` whose keys are all read from `ctx.config`, and import every name
|
`CONTRACT` whose keys are all read from `ctx.config`, and import every name
|
||||||
it uses. Returns the cleaned source. Raises ValueError otherwise.
|
it uses. Returns the cleaned source. Raises ValueError otherwise.
|
||||||
|
|
||||||
|
`max_chars` is the hard size ceiling (the scheduler derives it from the
|
||||||
|
active decision engine's context). A body over it raises `ArtifactTooLong`
|
||||||
|
so the retry ladder asks for a shorter one.
|
||||||
"""
|
"""
|
||||||
text = raw.strip()
|
text = raw.strip()
|
||||||
if "code" in text[:400] and "{" in text and "}" in text:
|
if "code" in text[:400] and "{" in text and "}" in text:
|
||||||
@@ -285,6 +304,12 @@ def parse_skill_body(raw: str) -> str:
|
|||||||
text = text.strip()
|
text = text.strip()
|
||||||
if not text:
|
if not text:
|
||||||
raise ValueError("skill body is empty")
|
raise ValueError("skill body is empty")
|
||||||
|
if max_chars is not None and len(text) > max_chars:
|
||||||
|
raise ArtifactTooLong(
|
||||||
|
f"skill body is {len(text)} chars, over the {max_chars}-char limit "
|
||||||
|
"for a decision-ingestible body; keep it small and delegate "
|
||||||
|
"protocol details to a bridge"
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
module = ast.parse(text, filename="<generated>")
|
module = ast.parse(text, filename="<generated>")
|
||||||
except SyntaxError as exc:
|
except SyntaxError as exc:
|
||||||
@@ -538,6 +563,82 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
|
|||||||
return findings
|
return findings
|
||||||
|
|
||||||
|
|
||||||
|
_HTTP_VERBS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
|
||||||
|
_SUBPROCESS_FUNCS = frozenset({"run", "Popen", "call", "check_call", "check_output"})
|
||||||
|
_FILE_WRITE_FUNCS = frozenset({"write_text", "write_bytes", "write"})
|
||||||
|
|
||||||
|
|
||||||
|
def _call_name(node) -> str:
|
||||||
|
"""Best-effort dotted name of a call target (e.g. `urllib.request.urlopen`)."""
|
||||||
|
parts: list[str] = []
|
||||||
|
while isinstance(node, ast.Attribute):
|
||||||
|
parts.append(node.attr)
|
||||||
|
node = node.value
|
||||||
|
if isinstance(node, ast.Name):
|
||||||
|
parts.append(node.id)
|
||||||
|
return ".".join(reversed(parts))
|
||||||
|
|
||||||
|
|
||||||
|
def operation_inventory(code: str) -> list[str]:
|
||||||
|
"""A compact, static inventory of the side-effecting operations in a body.
|
||||||
|
|
||||||
|
The fidelity gate reads the whole body; this inventory is its deterministic
|
||||||
|
companion. It names the concrete operations (HTTP verb + path, CLI run,
|
||||||
|
mail send, file write, timer) so the gate and its regen evidence see *what
|
||||||
|
the body does* at a glance, and a body that performs no operation at all is
|
||||||
|
legible immediately. Best-effort and purely static: a dynamic target
|
||||||
|
renders as `?`, an unparseable body yields nothing. Never raises.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
module = ast.parse(code, filename="<inventory>")
|
||||||
|
except SyntaxError:
|
||||||
|
return []
|
||||||
|
operations: list[str] = []
|
||||||
|
for node in ast.walk(module):
|
||||||
|
if not isinstance(node, ast.Call):
|
||||||
|
continue
|
||||||
|
name = _call_name(node.func)
|
||||||
|
leaf = name.rsplit(".", 1)[-1]
|
||||||
|
args = list(node.args) + [kw.value for kw in node.keywords]
|
||||||
|
strings = [s for a in args if (s := _const_str(a)) is not None]
|
||||||
|
verbs = [s for s in strings if s.upper() in _HTTP_VERBS]
|
||||||
|
if verbs:
|
||||||
|
paths = [s for s in strings if s.startswith("/")]
|
||||||
|
target = paths[0] if paths else "?"
|
||||||
|
operations.append(f"HTTP {verbs[0].upper()} {target} (via {name or '?'})")
|
||||||
|
continue
|
||||||
|
if name in {
|
||||||
|
"urllib.request.urlopen",
|
||||||
|
"urlopen",
|
||||||
|
"http.client.HTTPConnection",
|
||||||
|
"http.client.HTTPSConnection",
|
||||||
|
}:
|
||||||
|
operations.append(f"HTTP request (via {name})")
|
||||||
|
elif "subprocess" in name and leaf in _SUBPROCESS_FUNCS:
|
||||||
|
operations.append(f"run CLI (via {name})")
|
||||||
|
elif "smtplib" in name and leaf in {"sendmail", "send_message"}:
|
||||||
|
operations.append(f"send mail (via {name})")
|
||||||
|
elif "imaplib" in name and leaf in {"append", "store", "copy", "expunge"}:
|
||||||
|
operations.append(f"mail mutation (via {name})")
|
||||||
|
elif "poplib" in name and leaf in {"dele", "quit"}:
|
||||||
|
operations.append(f"mail mutation (via {name})")
|
||||||
|
elif leaf in _FILE_WRITE_FUNCS or (
|
||||||
|
name == "open"
|
||||||
|
and any(s in {"w", "a", "x", "wb", "ab", "xb", "w+", "a+", "wt", "at"} for s in strings)
|
||||||
|
):
|
||||||
|
operations.append(f"write file (via {name})")
|
||||||
|
elif name.startswith("ctx.timers"):
|
||||||
|
operations.append(f"schedule timer (via {name})")
|
||||||
|
if not operations:
|
||||||
|
operations.append("no side-effecting operation found")
|
||||||
|
return operations
|
||||||
|
|
||||||
|
|
||||||
|
def render_operation_inventory(operations: list[str]) -> str:
|
||||||
|
"""Render `operation_inventory` as a bulleted block for a decision state."""
|
||||||
|
return "\n".join(f"- {operation}" for operation in operations)
|
||||||
|
|
||||||
|
|
||||||
def _retry_prompt(
|
def _retry_prompt(
|
||||||
category: str,
|
category: str,
|
||||||
draft: SkillDraft,
|
draft: SkillDraft,
|
||||||
@@ -556,9 +657,17 @@ def _retry_prompt(
|
|||||||
"is authoritative: follow it exactly.\n\n"
|
"is authoritative: follow it exactly.\n\n"
|
||||||
f"{contract}"
|
f"{contract}"
|
||||||
)
|
)
|
||||||
|
if isinstance(error, ArtifactTooLong):
|
||||||
|
guidance = (
|
||||||
|
"The previous attempt was too long to fit the decision engine's "
|
||||||
|
"context. Emit a SHORTER body: keep `act` minimal and delegate "
|
||||||
|
"protocol details to a bridge.\n"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
guidance = "You are looping; emit the final Python now.\n"
|
||||||
user = (
|
user = (
|
||||||
f"The previous attempt to write the skill body for {category}.{draft.name} "
|
f"The previous attempt to write the skill body for {category}.{draft.name} "
|
||||||
f"was rejected: {error}. You are looping; emit the final Python now.\n"
|
f"was rejected: {error}. {guidance}"
|
||||||
f"Category: {category}\n"
|
f"Category: {category}\n"
|
||||||
f"Skill name: {draft.name}\n"
|
f"Skill name: {draft.name}\n"
|
||||||
f"Reusable goal (de-identified): {draft.goal}\n"
|
f"Reusable goal (de-identified): {draft.goal}\n"
|
||||||
@@ -583,6 +692,7 @@ def generate_skill_body(
|
|||||||
contract: str | None = None,
|
contract: str | None = None,
|
||||||
max_tokens: int | None = None,
|
max_tokens: int | None = None,
|
||||||
degeneration_check: Callable[[str], str | None] | None = None,
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
max_chars: int | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Author a skill body with the big model; retry up to `max_attempts`.
|
"""Author a skill body with the big model; retry up to `max_attempts`.
|
||||||
|
|
||||||
@@ -618,7 +728,7 @@ def generate_skill_body(
|
|||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
degeneration_check=degeneration_check,
|
degeneration_check=degeneration_check,
|
||||||
)
|
)
|
||||||
return parse_skill_body(raw)
|
return parse_skill_body(raw, max_chars=max_chars)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
last_error = exc
|
last_error = exc
|
||||||
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
||||||
@@ -756,12 +866,12 @@ def build_testgen_request_prompt(
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def parse_skill_test(raw: str) -> str:
|
def parse_skill_test(raw: str, max_chars: int | None = None) -> str:
|
||||||
"""Extract and validate skill.test.py from the model's reply.
|
"""Extract and validate skill.test.py from the model's reply.
|
||||||
|
|
||||||
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The test
|
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The test
|
||||||
must parse as Python. Returns the cleaned source. Raises ValueError
|
must parse as Python and (when `max_chars` is set) fit the artifact size
|
||||||
otherwise.
|
budget. Returns the cleaned source. Raises ValueError otherwise.
|
||||||
"""
|
"""
|
||||||
text = raw.strip()
|
text = raw.strip()
|
||||||
if "code" in text[:400] and "{" in text and "}" in text:
|
if "code" in text[:400] and "{" in text and "}" in text:
|
||||||
@@ -784,6 +894,11 @@ def parse_skill_test(raw: str) -> str:
|
|||||||
text = text.strip()
|
text = text.strip()
|
||||||
if not text:
|
if not text:
|
||||||
raise ValueError("skill test is empty")
|
raise ValueError("skill test is empty")
|
||||||
|
if max_chars is not None and len(text) > max_chars:
|
||||||
|
raise ArtifactTooLong(
|
||||||
|
f"skill test is {len(text)} chars, over the {max_chars}-char limit "
|
||||||
|
"for a codegen artifact; keep fixtures compact"
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
ast.parse(text, filename="<generated test>")
|
ast.parse(text, filename="<generated test>")
|
||||||
except SyntaxError as exc:
|
except SyntaxError as exc:
|
||||||
@@ -800,6 +915,7 @@ def generate_skill_tests(
|
|||||||
contract_md: str | None = None,
|
contract_md: str | None = None,
|
||||||
reason: str | None = None,
|
reason: str | None = None,
|
||||||
target: str | None = None,
|
target: str | None = None,
|
||||||
|
max_chars: int | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Generate skill.test.py against the finished body.
|
"""Generate skill.test.py against the finished body.
|
||||||
|
|
||||||
@@ -828,7 +944,7 @@ def generate_skill_tests(
|
|||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
raw = client.chat(messages)
|
raw = client.chat(messages)
|
||||||
return parse_skill_test(raw)
|
return parse_skill_test(raw, max_chars=max_chars)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
last_error = exc
|
last_error = exc
|
||||||
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
|
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
|
||||||
@@ -901,6 +1017,7 @@ def regenerate_skill_body(
|
|||||||
evidence: dict,
|
evidence: dict,
|
||||||
contract: str | None = None,
|
contract: str | None = None,
|
||||||
reason_kind: str = "test",
|
reason_kind: str = "test",
|
||||||
|
max_chars: int | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Rewrite a skill body whose test, review, or real run failed.
|
"""Rewrite a skill body whose test, review, or real run failed.
|
||||||
|
|
||||||
@@ -925,7 +1042,7 @@ def regenerate_skill_body(
|
|||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
raw = client.chat(messages)
|
raw = client.chat(messages)
|
||||||
return parse_skill_body(raw)
|
return parse_skill_body(raw, max_chars=max_chars)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
last_error = exc
|
last_error = exc
|
||||||
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
||||||
|
|||||||
@@ -52,6 +52,17 @@ class DecisionEngine(ABC):
|
|||||||
|
|
||||||
label: str = "engine"
|
label: str = "engine"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def context_tokens(self) -> int:
|
||||||
|
"""The decision context window, in tokens.
|
||||||
|
|
||||||
|
Every decision state must fit inside it, so the scheduler sizes the
|
||||||
|
generated skill bodies it feeds the fidelity gate from this value. A
|
||||||
|
provider that does not expose its window keeps the conservative local
|
||||||
|
default (the local 4B engine's `engine.context_tokens`).
|
||||||
|
"""
|
||||||
|
return 4096
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def loaded(self) -> bool:
|
def loaded(self) -> bool:
|
||||||
@@ -210,6 +221,10 @@ class SemIfEngine(DecisionEngine):
|
|||||||
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
|
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
|
||||||
return model, tokenizer, metadata
|
return model, tokenizer, metadata
|
||||||
|
|
||||||
|
@property
|
||||||
|
def context_tokens(self) -> int:
|
||||||
|
return int(self.config.context_tokens or 4096)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def loaded(self) -> bool:
|
def loaded(self) -> bool:
|
||||||
return self._model is not None
|
return self._model is not None
|
||||||
|
|||||||
+78
-13
@@ -26,8 +26,10 @@ from .codegen import (
|
|||||||
generate_skill_body,
|
generate_skill_body,
|
||||||
generate_skill_tests,
|
generate_skill_tests,
|
||||||
integration_findings,
|
integration_findings,
|
||||||
|
operation_inventory,
|
||||||
parse_contract,
|
parse_contract,
|
||||||
regenerate_skill_body,
|
regenerate_skill_body,
|
||||||
|
render_operation_inventory,
|
||||||
run_skill_test,
|
run_skill_test,
|
||||||
skill_contract_ref,
|
skill_contract_ref,
|
||||||
)
|
)
|
||||||
@@ -76,6 +78,32 @@ from .trace import TraceLog
|
|||||||
#: `data/skills/<category>/config.json` (same key).
|
#: `data/skills/<category>/config.json` (same key).
|
||||||
NEW_SKILL_MODES = ("allow", "deny", "ask")
|
NEW_SKILL_MODES = ("allow", "deny", "ask")
|
||||||
|
|
||||||
|
#: Hard floor for a derived artifact budget, so a misconfigured (tiny) engine
|
||||||
|
#: context cannot collapse the codegen ceiling to something unusable.
|
||||||
|
MIN_ARTIFACT_TOKENS = 256
|
||||||
|
|
||||||
|
|
||||||
|
def artifact_token_budget(override, engine_context: int, reserve: int) -> int:
|
||||||
|
"""The token budget for one generated artifact (skill body or test).
|
||||||
|
|
||||||
|
A positive `override` (the `codegen.max_body_tokens` / `max_test_tokens`
|
||||||
|
config value) wins — a user lowers it to avoid waiting on a long fidelity
|
||||||
|
evaluation, or raises it when the deployment's engine has a larger window.
|
||||||
|
Otherwise it is derived from the active engine's decision context minus the
|
||||||
|
reserved headroom for everything else in the decision state (the goal,
|
||||||
|
description, integration, findings, operation inventory, the question and
|
||||||
|
options, and the engine's prefill margin): the codegen runs immediately
|
||||||
|
before the fidelity gate, so that non-body context is already known. A hard
|
||||||
|
floor keeps the result usable.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
value = int(override or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
value = 0
|
||||||
|
if value > 0:
|
||||||
|
return value
|
||||||
|
return max(int(engine_context) - int(reserve), MIN_ARTIFACT_TOKENS)
|
||||||
|
|
||||||
|
|
||||||
def normalize_new_skill_mode(value) -> str | None:
|
def normalize_new_skill_mode(value) -> str | None:
|
||||||
"""Coerce a configured new-skill mode to one of `NEW_SKILL_MODES`.
|
"""Coerce a configured new-skill mode to one of `NEW_SKILL_MODES`.
|
||||||
@@ -338,6 +366,10 @@ class Scheduler:
|
|||||||
fidelity_cfg = codegen_cfg.get("fidelity", {}) or {}
|
fidelity_cfg = codegen_cfg.get("fidelity", {}) or {}
|
||||||
self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True))
|
self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True))
|
||||||
self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1))
|
self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1))
|
||||||
|
#: The fidelity gate's own threshold, separate from the top-level `tau`
|
||||||
|
#: so tuning run assessment does not move the real-action gate. Defaults
|
||||||
|
#: to `tau` when unset.
|
||||||
|
self.fidelity_tau = float(fidelity_cfg.get("tau", self.tau))
|
||||||
repair_cfg = codegen_cfg.get("repair", {}) or {}
|
repair_cfg = codegen_cfg.get("repair", {}) or {}
|
||||||
self.repair_enabled = bool(repair_cfg.get("enabled", True))
|
self.repair_enabled = bool(repair_cfg.get("enabled", True))
|
||||||
self.repair_max_attempts = int(repair_cfg.get("max_attempts", 1))
|
self.repair_max_attempts = int(repair_cfg.get("max_attempts", 1))
|
||||||
@@ -346,6 +378,25 @@ class Scheduler:
|
|||||||
self.contract_search = bool(
|
self.contract_search = bool(
|
||||||
(codegen_cfg.get("contract_search", {}) or {}).get("enabled", True)
|
(codegen_cfg.get("contract_search", {}) or {}).get("enabled", True)
|
||||||
)
|
)
|
||||||
|
#: Generated artifacts are ingested *whole* by a decision (the fidelity
|
||||||
|
#: gate reads the entire skill body), so their size is bounded by the
|
||||||
|
#: active engine's decision context minus headroom for the rest of the
|
||||||
|
#: state. Derived here because codegen runs immediately before the gate,
|
||||||
|
#: so the non-body context is already known; a positive config value
|
||||||
|
#: overrides (lower it to avoid a long fidelity evaluation).
|
||||||
|
self.chars_per_token = float(codegen_cfg.get("chars_per_token", 4.0) or 4.0)
|
||||||
|
self.decision_reserve_tokens = max(
|
||||||
|
0, int(codegen_cfg.get("decision_reserve_tokens", 1024))
|
||||||
|
)
|
||||||
|
engine_context = int(getattr(engine, "context_tokens", 4096) or 4096)
|
||||||
|
self.max_body_tokens = artifact_token_budget(
|
||||||
|
codegen_cfg.get("max_body_tokens"), engine_context, self.decision_reserve_tokens
|
||||||
|
)
|
||||||
|
self.max_test_tokens = artifact_token_budget(
|
||||||
|
codegen_cfg.get("max_test_tokens"), engine_context, self.decision_reserve_tokens
|
||||||
|
)
|
||||||
|
self.max_body_chars = int(self.max_body_tokens * self.chars_per_token)
|
||||||
|
self.max_test_chars = int(self.max_test_tokens * self.chars_per_token)
|
||||||
self.queue = RequestQueue(
|
self.queue = RequestQueue(
|
||||||
max_size=int(config.get("queue", {}).get("max_size", 100)),
|
max_size=int(config.get("queue", {}).get("max_size", 100)),
|
||||||
)
|
)
|
||||||
@@ -1735,6 +1786,7 @@ class Scheduler:
|
|||||||
self._read_body(job.category, job.draft.name),
|
self._read_body(job.category, job.draft.name),
|
||||||
evidence,
|
evidence,
|
||||||
reason_kind=job.reason_kind,
|
reason_kind=job.reason_kind,
|
||||||
|
max_chars=self.max_body_chars,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
code = generate_skill_body(
|
code = generate_skill_body(
|
||||||
@@ -1747,6 +1799,7 @@ class Scheduler:
|
|||||||
if self.degeneration_check_factory is not None
|
if self.degeneration_check_factory is not None
|
||||||
else None
|
else None
|
||||||
),
|
),
|
||||||
|
max_chars=self.max_body_chars,
|
||||||
)
|
)
|
||||||
code = self._fidelity_gate(job, code)
|
code = self._fidelity_gate(job, code)
|
||||||
contract = parse_contract(code)
|
contract = parse_contract(code)
|
||||||
@@ -1784,13 +1837,18 @@ class Scheduler:
|
|||||||
"""Rapid SemIf sanity gate on the body; regen once only on reconsider.
|
"""Rapid SemIf sanity gate on the body; regen once only on reconsider.
|
||||||
|
|
||||||
`authoring:fidelity` (accept/reconsider) runs beside static findings
|
`authoring:fidelity` (accept/reconsider) runs beside static findings
|
||||||
(declaration vs. code). A non-empty findings list forces reconsider.
|
(declaration vs. code). The state carries the **whole** body — the gate
|
||||||
The gate never diagnoses: it only triggers a rewrite, which is handed
|
ingests the artifact verbatim, which is why generated bodies are
|
||||||
the raw evidence bundle as-is. Bounded by
|
size-bounded (`max_body_chars`) — plus a deterministic operation
|
||||||
`codegen.fidelity.max_attempts`; a body that still fails is accepted
|
inventory and the de-identified goal. It asks the positive question (is
|
||||||
(never hard-fail authoring) but traced and badged `unverified`. The
|
there a concrete operation that realizes the goal?) rather than asking
|
||||||
engine is real: an EngineUnavailable propagates and the worker marks
|
the model to prove a negative, and uses its own `fidelity_tau` rather
|
||||||
the app fatal.
|
than the run-assessment `tau`. A non-empty findings list forces
|
||||||
|
reconsider. The gate never diagnoses: on reject the rewrite is handed
|
||||||
|
the raw evidence bundle (inventory + findings included) as-is. Bounded
|
||||||
|
by `codegen.fidelity.max_attempts`; a body that still fails is accepted
|
||||||
|
(never hard-fail authoring) but traced. The engine is real: an
|
||||||
|
EngineUnavailable propagates and the worker marks the app fatal.
|
||||||
"""
|
"""
|
||||||
if not self.fidelity_enabled or self.codegen is None:
|
if not self.fidelity_enabled or self.codegen is None:
|
||||||
return code
|
return code
|
||||||
@@ -1799,18 +1857,22 @@ class Scheduler:
|
|||||||
attempts = max(self.fidelity_max_attempts, 0)
|
attempts = max(self.fidelity_max_attempts, 0)
|
||||||
reviewed = code
|
reviewed = code
|
||||||
for attempt in range(attempts + 1):
|
for attempt in range(attempts + 1):
|
||||||
|
inventory = operation_inventory(reviewed)
|
||||||
decision = DecisionRequest(
|
decision = DecisionRequest(
|
||||||
state=(
|
state=(
|
||||||
f"[authoring fidelity] skill {job.category}.{job.draft.name}\n"
|
f"[authoring fidelity] skill {job.category}.{job.draft.name}\n"
|
||||||
f"request: {job.request.text}\n"
|
f"goal: {job.draft.goal}\n"
|
||||||
f"description: {job.draft.description}\n"
|
f"description: {job.draft.description}\n"
|
||||||
f"INTEGRATION: {json.dumps(integration, sort_keys=True)}\n"
|
f"INTEGRATION: {json.dumps(integration, sort_keys=True)}\n"
|
||||||
f"findings: {json.dumps(findings)}\n"
|
f"findings: {json.dumps(findings)}\n"
|
||||||
f"body:\n{reviewed[:4000]}"
|
f"observed operations (static inventory):\n"
|
||||||
|
f"{render_operation_inventory(inventory)}\n"
|
||||||
|
f"body:\n{reviewed}"
|
||||||
),
|
),
|
||||||
question=(
|
question=(
|
||||||
"Does this skill body really perform the requested action "
|
"Does this skill body contain a concrete, side-effecting "
|
||||||
"against the user's service, or does it simulate it?"
|
"operation that really performs its goal against the user's "
|
||||||
|
"service (not a simulation, canned result, or draft)?"
|
||||||
),
|
),
|
||||||
options=[
|
options=[
|
||||||
Option("accept", "It really performs the action."),
|
Option("accept", "It really performs the action."),
|
||||||
@@ -1818,7 +1880,7 @@ class Scheduler:
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
result = self.engine.call(decision)
|
result = self.engine.call(decision)
|
||||||
reconsider = result.prob("reconsider") >= self.tau or bool(findings)
|
reconsider = result.prob("reconsider") >= self.fidelity_tau or bool(findings)
|
||||||
self.log.append(
|
self.log.append(
|
||||||
decision,
|
decision,
|
||||||
result,
|
result,
|
||||||
@@ -1852,6 +1914,7 @@ class Scheduler:
|
|||||||
"description": job.draft.description,
|
"description": job.draft.description,
|
||||||
"INTEGRATION": integration,
|
"INTEGRATION": integration,
|
||||||
"findings": findings,
|
"findings": findings,
|
||||||
|
"observed_operations": inventory,
|
||||||
"verdict": result.selected,
|
"verdict": result.selected,
|
||||||
"probabilities": result.probs,
|
"probabilities": result.probs,
|
||||||
"previous_body": reviewed,
|
"previous_body": reviewed,
|
||||||
@@ -1864,6 +1927,7 @@ class Scheduler:
|
|||||||
reviewed,
|
reviewed,
|
||||||
evidence,
|
evidence,
|
||||||
reason_kind="fidelity",
|
reason_kind="fidelity",
|
||||||
|
max_chars=self.max_body_chars,
|
||||||
)
|
)
|
||||||
except (CodegenError, ValueError) as exc:
|
except (CodegenError, ValueError) as exc:
|
||||||
self.trace.append(
|
self.trace.append(
|
||||||
@@ -1905,13 +1969,14 @@ class Scheduler:
|
|||||||
"previous_body": code,
|
"previous_body": code,
|
||||||
},
|
},
|
||||||
reason_kind="test",
|
reason_kind="test",
|
||||||
|
max_chars=self.max_body_chars,
|
||||||
)
|
)
|
||||||
self.body_store.write_body(job.category, job.draft.name, code)
|
self.body_store.write_body(job.category, job.draft.name, code)
|
||||||
contract = parse_contract(code)
|
contract = parse_contract(code)
|
||||||
self.body_store.write_contract(job.category, job.draft.name, contract)
|
self.body_store.write_contract(job.category, job.draft.name, contract)
|
||||||
test = generate_skill_tests(
|
test = generate_skill_tests(
|
||||||
self.codegen, job.category, job.draft, code, contract,
|
self.codegen, job.category, job.draft, code, contract,
|
||||||
reason=reason, target=target,
|
reason=reason, target=target, max_chars=self.max_test_chars,
|
||||||
)
|
)
|
||||||
self.body_store.write_test(job.category, job.draft.name, test)
|
self.body_store.write_test(job.category, job.draft.name, test)
|
||||||
passed, output = run_skill_test(
|
passed, output = run_skill_test(
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ class WinnowConfig:
|
|||||||
|
|
||||||
base_url: str = "http://127.0.0.1:8091"
|
base_url: str = "http://127.0.0.1:8091"
|
||||||
model: str = "Winnow-12B"
|
model: str = "Winnow-12B"
|
||||||
|
#: The server's decision context window (`--ctx-size`). Must mirror the
|
||||||
|
#: running server; used to size generated skill bodies so a fidelity state
|
||||||
|
#: always fits. The reference deployment runs `--ctx-size 32768`.
|
||||||
|
context_tokens: int = 32768
|
||||||
timeout: float = 120.0
|
timeout: float = 120.0
|
||||||
# Transient-failure retries before declaring the engine unavailable. 0 means
|
# Transient-failure retries before declaring the engine unavailable. 0 means
|
||||||
# a single attempt: an unreachable remote engine is fatal by contract.
|
# a single attempt: an unreachable remote engine is fatal by contract.
|
||||||
@@ -59,6 +63,10 @@ class WinnowEngine(DecisionEngine):
|
|||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._loaded = False
|
self._loaded = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def context_tokens(self) -> int:
|
||||||
|
return int(self.config.context_tokens or 32768)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def loaded(self) -> bool:
|
def loaded(self) -> bool:
|
||||||
return self._loaded
|
return self._loaded
|
||||||
|
|||||||
@@ -529,6 +529,78 @@ def act(ctx, request):
|
|||||||
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
|
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
|
||||||
print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
|
print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
|
||||||
assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
|
assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
|
||||||
|
assert rows[-1]["extra"]["reconsider"] is False, (
|
||||||
|
"a declared body with a real transport call must be accepted"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fidelity_gate_reads_the_whole_body(tmp_path):
|
||||||
|
"""Regression: the gate ingests the WHOLE body, never a prefix.
|
||||||
|
|
||||||
|
A body whose real action sits *after* the old 4000-char cutoff (helpers and
|
||||||
|
padding first) must be accepted by the real engine. Before the fix the gate
|
||||||
|
saw only a prefix that contained no action and wrongly returned
|
||||||
|
`reconsider`; the raw request must also stay out of the state.
|
||||||
|
"""
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
_isolate_runtime(config, tmp_path)
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
scheduler.codegen = CodegenClient(
|
||||||
|
base_url="http://127.0.0.1:1/v1", model="test", timeout=2
|
||||||
|
)
|
||||||
|
|
||||||
|
padding = "# filler to push the real action past the old 4000-char cutoff\n"
|
||||||
|
body = (
|
||||||
|
'"""Check a delivery through the carrier HTTP API."""\n\n'
|
||||||
|
'INTEGRATION = {"service": "carrier", "transport": "http", '
|
||||||
|
'"config_vars": ["tracking_url"]}\n'
|
||||||
|
'CONTRACT = {"tracking_url": "Carrier status endpoint."}\n\n'
|
||||||
|
"import json\n"
|
||||||
|
"import urllib.request\n\n"
|
||||||
|
"from semif_agent.skills import ActionResult\n\n\n"
|
||||||
|
+ padding * 60
|
||||||
|
+ "def _post(ctx, path, payload):\n"
|
||||||
|
" req = urllib.request.Request(\n"
|
||||||
|
' ctx.config["tracking_url"] + path,\n'
|
||||||
|
" data=json.dumps(payload).encode(),\n"
|
||||||
|
' method="POST",\n'
|
||||||
|
" )\n"
|
||||||
|
" with urllib.request.urlopen(req, timeout=15) as response:\n"
|
||||||
|
' return json.loads(response.read().decode("utf-8"))\n\n\n'
|
||||||
|
"def act(ctx, request):\n"
|
||||||
|
' reply = _post(ctx, "/deliveries/check", {"id": "1"})\n'
|
||||||
|
" return ActionResult(\n"
|
||||||
|
' action_log=f"carrier said {reply[\'status\']}",\n'
|
||||||
|
' new_state=reply["status"],\n'
|
||||||
|
" )\n"
|
||||||
|
)
|
||||||
|
assert body.index('method="POST"') > 4000, "fixture must place the action past the old cutoff"
|
||||||
|
|
||||||
|
job = SkillWrite(
|
||||||
|
request=Request("check my delivery status for package 12345"),
|
||||||
|
category="tracking",
|
||||||
|
draft=SkillDraft(
|
||||||
|
name="check_delivery",
|
||||||
|
description="Check a package's delivery status.",
|
||||||
|
goal="POST the carrier's check endpoint and report the observed status.",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
scheduler._fidelity_gate(job, body)
|
||||||
|
row = [
|
||||||
|
r
|
||||||
|
for r in scheduler.log.read()
|
||||||
|
if r.get("extra", {}).get("phase") == "authoring:fidelity"
|
||||||
|
][-1]
|
||||||
|
print(f"whole-body reconsider: {row['extra']['reconsider']} {row['predicted_probs']}")
|
||||||
|
assert row["extra"]["findings"] == [], "a consistent declaration has no findings"
|
||||||
|
assert row["extra"]["reconsider"] is False, (
|
||||||
|
"the gate must see the action and accept the body (whole-body ingestion)"
|
||||||
|
)
|
||||||
|
assert 'method="POST"' in row["state"], "the whole body must reach the gate"
|
||||||
|
assert "check my delivery status for package 12345" not in row["state"], (
|
||||||
|
"the raw request must not reach the gate"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import pytest
|
|||||||
|
|
||||||
from semif_agent.codegen import (
|
from semif_agent.codegen import (
|
||||||
BODY_DIRECTIVES,
|
BODY_DIRECTIVES,
|
||||||
|
ArtifactTooLong,
|
||||||
CodegenClient,
|
CodegenClient,
|
||||||
CodegenError,
|
CodegenError,
|
||||||
DegenerationError,
|
DegenerationError,
|
||||||
@@ -28,6 +29,7 @@ from semif_agent.codegen import (
|
|||||||
generate_skill_tests,
|
generate_skill_tests,
|
||||||
infer_integration,
|
infer_integration,
|
||||||
integration_findings,
|
integration_findings,
|
||||||
|
operation_inventory,
|
||||||
parse_contract,
|
parse_contract,
|
||||||
parse_integration,
|
parse_integration,
|
||||||
parse_skill_body,
|
parse_skill_body,
|
||||||
@@ -35,6 +37,7 @@ from semif_agent.codegen import (
|
|||||||
read_skill_contract,
|
read_skill_contract,
|
||||||
read_testgen_contract,
|
read_testgen_contract,
|
||||||
regenerate_skill_body,
|
regenerate_skill_body,
|
||||||
|
render_operation_inventory,
|
||||||
run_skill_test,
|
run_skill_test,
|
||||||
skill_contract_ref,
|
skill_contract_ref,
|
||||||
)
|
)
|
||||||
@@ -1930,3 +1933,83 @@ def test_testgen_prompt_requires_loopback_fixture_and_hermeticity():
|
|||||||
assert "HERMETIC" in joined
|
assert "HERMETIC" in joined
|
||||||
assert "loopback" in joined
|
assert "loopback" in joined
|
||||||
assert "never simulate the action" in joined.lower()
|
assert "never simulate the action" in joined.lower()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- artifact size budget + operation inventory ----
|
||||||
|
|
||||||
|
def test_parse_skill_body_enforces_size_budget():
|
||||||
|
"""A body over the decision-ingestible ceiling is rejected as too long.
|
||||||
|
|
||||||
|
The ceiling is hard because a decision (the fidelity gate) reads the body
|
||||||
|
whole; the retry ladder then asks for a shorter one.
|
||||||
|
"""
|
||||||
|
assert parse_skill_body(GOOD_BODY, max_chars=100000) == GOOD_BODY.strip()
|
||||||
|
with pytest.raises(ArtifactTooLong):
|
||||||
|
parse_skill_body(GOOD_BODY, max_chars=len(GOOD_BODY) // 2)
|
||||||
|
# No limit means no rejection.
|
||||||
|
assert parse_skill_body(GOOD_BODY) == GOOD_BODY.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_skill_test_enforces_size_budget():
|
||||||
|
assert parse_skill_test(GOOD_TEST, max_chars=100000) == GOOD_TEST.strip()
|
||||||
|
with pytest.raises(ArtifactTooLong):
|
||||||
|
parse_skill_test(GOOD_TEST, max_chars=10)
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_prompt_asks_for_a_shorter_body_when_too_long():
|
||||||
|
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||||
|
too_long = _retry_prompt("probe", draft, "CONTRACT", ArtifactTooLong("too long"))
|
||||||
|
assert "SHORTER" in json.dumps(too_long)
|
||||||
|
looping = _retry_prompt("probe", draft, "CONTRACT", ValueError("bad shape"))
|
||||||
|
assert "looping" in json.dumps(looping)
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_inventory_finds_http_verb_and_path_via_helper():
|
||||||
|
"""The verb + path live at the call site, not the transport helper: the
|
||||||
|
inventory must surface `POST /tasks/complete` for a thin-helper body."""
|
||||||
|
code = '''\
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
|
||||||
|
def _bridge(ctx, method, path, payload=None):
|
||||||
|
return urllib.request.urlopen(path)
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
_bridge(ctx, "POST", "/tasks/complete", payload={"uid": "1"})
|
||||||
|
return ActionResult(action_log="ok", new_state="ok")
|
||||||
|
'''
|
||||||
|
ops = operation_inventory(code)
|
||||||
|
assert any("HTTP POST /tasks/complete" in op for op in ops), ops
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_inventory_flags_a_body_with_no_action():
|
||||||
|
code = '''\
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="done", new_state="done")
|
||||||
|
'''
|
||||||
|
assert operation_inventory(code) == ["no side-effecting operation found"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_inventory_detects_subprocess_and_file_write():
|
||||||
|
code = '''\
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
subprocess.run(["/bin/ps", "-e"])
|
||||||
|
with open("out.txt", "w") as handle:
|
||||||
|
handle.write("x")
|
||||||
|
'''
|
||||||
|
ops = operation_inventory(code)
|
||||||
|
assert any("run CLI" in op for op in ops), ops
|
||||||
|
assert any("write file" in op for op in ops), ops
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_operation_inventory_is_bulleted():
|
||||||
|
assert render_operation_inventory(["a", "b"]) == "- a\n- b"
|
||||||
@@ -24,12 +24,14 @@ from semif_agent.llm import LLMClient, LLMError
|
|||||||
from semif_agent.log import DecisionLog
|
from semif_agent.log import DecisionLog
|
||||||
from semif_agent.skill import RunResult
|
from semif_agent.skill import RunResult
|
||||||
from semif_agent.scheduler import (
|
from semif_agent.scheduler import (
|
||||||
|
MIN_ARTIFACT_TOKENS,
|
||||||
DraftAuthor,
|
DraftAuthor,
|
||||||
PendingQuestion,
|
PendingQuestion,
|
||||||
RepairOffer,
|
RepairOffer,
|
||||||
Scheduler,
|
Scheduler,
|
||||||
SchedulerReply,
|
SchedulerReply,
|
||||||
SkillWrite,
|
SkillWrite,
|
||||||
|
artifact_token_budget,
|
||||||
)
|
)
|
||||||
from semif_agent.skills import (
|
from semif_agent.skills import (
|
||||||
ActionResult,
|
ActionResult,
|
||||||
@@ -157,6 +159,66 @@ def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosit
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_artifact_token_budget_derives_overrides_and_floors():
|
||||||
|
"""The artifact ceiling is the engine context minus the reserve; a positive
|
||||||
|
config value overrides it; a hard floor keeps it usable."""
|
||||||
|
assert artifact_token_budget(0, 32768, 1024) == 32768 - 1024
|
||||||
|
assert artifact_token_budget(None, 4096, 1024) == 4096 - 1024
|
||||||
|
assert artifact_token_budget(2000, 32768, 1024) == 2000
|
||||||
|
assert artifact_token_budget(0, 100, 1024) == MIN_ARTIFACT_TOKENS
|
||||||
|
|
||||||
|
|
||||||
|
def test_scheduler_sizes_artifact_budgets_from_engine_context(tmp_path):
|
||||||
|
"""Body/test char ceilings are derived from the active engine's context."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
# ScriptedEngine exposes no context_tokens -> the conservative 4096 default.
|
||||||
|
assert scheduler.max_body_tokens == 4096 - 1024
|
||||||
|
assert scheduler.max_body_chars == int((4096 - 1024) * 4.0)
|
||||||
|
assert scheduler.max_test_chars == scheduler.max_body_chars
|
||||||
|
|
||||||
|
|
||||||
|
def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path):
|
||||||
|
"""The gate ingests the whole body plus the inventory and goal, and never
|
||||||
|
the raw user request (the truncation bug and the PII path, both fixed)."""
|
||||||
|
scheduler = _scheduler(
|
||||||
|
tmp_path,
|
||||||
|
codegen=CodegenClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=1),
|
||||||
|
)
|
||||||
|
body = '''\
|
||||||
|
INTEGRATION = {"service": "nextcloud", "transport": "http", "config_vars": ["nextcloud_bridge_url"]}
|
||||||
|
CONTRACT = {"nextcloud_bridge_url": "Bridge URL."}
|
||||||
|
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
|
||||||
|
def _bridge(ctx, method, path, payload=None):
|
||||||
|
return urllib.request.urlopen(ctx.config["nextcloud_bridge_url"] + path)
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
_bridge(ctx, "POST", "/tasks/complete", payload={"uid": "1"})
|
||||||
|
return ActionResult(action_log="done", new_state="done")
|
||||||
|
'''
|
||||||
|
job = SkillWrite(
|
||||||
|
request=Request("mark task Eat hot dogs as completed"),
|
||||||
|
category="nextcloud",
|
||||||
|
draft=SkillDraft(
|
||||||
|
name="update_task_status",
|
||||||
|
description="Marks a task completed.",
|
||||||
|
goal="Update a task's status to completed.",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
scheduler._fidelity_gate(job, body)
|
||||||
|
state = scheduler.engine.calls[-1].state
|
||||||
|
assert "/tasks/complete" in state, "the whole body must be present"
|
||||||
|
assert "POST /tasks/complete" in state, "the inventory must name the action"
|
||||||
|
assert "observed operations" in state
|
||||||
|
assert "Update a task's status to completed." in state
|
||||||
|
assert "Eat hot dogs" not in state, "the raw request must not reach the gate"
|
||||||
|
|
||||||
|
|
||||||
def test_action_result_needs_input_defaults_none():
|
def test_action_result_needs_input_defaults_none():
|
||||||
assert ActionResult("log", "state").needs_input is None
|
assert ActionResult("log", "state").needs_input is None
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user