From c69930dfdba3cdaba28b0f7f18abd7a1b9a702e3 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 11:04:42 +0800 Subject: [PATCH 01/26] feat(intake): add intake/v1 confirmation records and a campaign start gate A vague request such as "make the service faster without losing quality" reaches campaign start with no record of which conditions the user stated. Add a host-independent intake record that a question card and a numbered text fallback both write, so missing inputs are asked once and kept. - apps/cli/intake_contract.py: pure functions for question selection by batch and dependency, answers, stale and duplicate rejection, frozen gate comparison and the derived allowed next stages. - task-performance and task-day-0 field specs next to their skills. - task intake evaluate / answer / summary commands. - campaign start --intake refuses an incomplete task-performance record before writing anything and retains the gated record with its digest. An acceptance value is confirmed only when its declared source is the acceptance issue or the frozen gate record; a card answer stays a proposal and does not unblock candidate search. Without --intake, campaign start warns and proceeds as before. Agent-assisted-by: Claude Code / claude-fable-5-2 [effort=xhigh] (author) Co-Authored-By: Claude Fable 5.2 Signed-off-by: jiangkuaixue123 --- docs/guides/operations.md | 1 + docs/guides/task-input.md | 3 + docs/guides/task-intake.md | 144 +++++ plugins/inferrsi/skills/inferrsi/SKILL.md | 22 + src/inferrsi/apps/cli/__init__.py | 27 +- src/inferrsi/apps/cli/arguments.py | 36 +- src/inferrsi/apps/cli/intake_contract.py | 590 ++++++++++++++++++ src/inferrsi/apps/cli/task_intake.py | 263 ++++++++ .../tasks/inference-task-router/SKILL.md | 2 + .../tasks/task-day-0/intake.json | 63 ++ .../tasks/task-performance/SKILL.md | 6 +- .../tasks/task-performance/intake.json | 233 +++++++ tests/apps/test_task_intake.py | 372 +++++++++++ .../fixtures/intake/performance/complete.json | 38 ++ .../intake/performance/frozen-gate.yaml | 8 + .../intake/performance/frozen-mismatch.yaml | 8 + .../fixtures/intake/performance/partial.json | 15 + 17 files changed, 1828 insertions(+), 3 deletions(-) create mode 100644 docs/guides/task-intake.md create mode 100644 src/inferrsi/apps/cli/intake_contract.py create mode 100644 src/inferrsi/apps/cli/task_intake.py create mode 100644 src/inferrsi/knowledge/data/skill_library/tasks/task-day-0/intake.json create mode 100644 src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json create mode 100644 tests/apps/test_task_intake.py create mode 100644 tests/fixtures/intake/performance/complete.json create mode 100644 tests/fixtures/intake/performance/frozen-gate.yaml create mode 100644 tests/fixtures/intake/performance/frozen-mismatch.yaml create mode 100644 tests/fixtures/intake/performance/partial.json diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 24a168e62..36e133281 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -33,6 +33,7 @@ Effect classes used below: | Inspect a store candidate's history | Python `open_knowledge_store(...).history` | Read-only | Opens an existing store and reads the revision lineage for one store ID | | Amend repository-owned knowledge | Scoped repository PR | — | Repository review and integration authority apply; this is not a runtime store Update | | Validate or preview a YAML task file | CLI `task validate` / `task preview [--json]` / `task schema` / `task template`; [task input](task-input.md) | Read-only | Reads one schema v1 task file and prints field errors, effective normalized values, their sources and plan/run blockers. Starts no process or probe and writes no workspace, plan, run or evidence file. A complete preview does not authorize execution | +| Confirm missing inputs before a measured task | CLI `task intake evaluate` / `answer` / `summary [--json]`; `campaign start --intake`; [task intake](task-intake.md) | Local record | Evaluates an intake/v1 record against the packaged field spec and returns the questions that unblock the next stage. `evaluate` and `answer` write only the caller-named record file; `summary` reads. Starts no process or probe. A complete record does not authorize execution or freeze a gate | | Inspect/prepare experiments | CLI `doctor`; `plan` or `--dry-run` | Read-only inspection / preview | `doctor` may invoke bounded probes and does not certify target compatibility; `plan` previews a specification without persisting a campaign or authorizing execution | | Execute/inspect experiments | CLI `run`; `status`; `report` | Experiment-executing / read-only / report-generating | `run` executes caller-supplied commands and records evidence; `status` reads recorded progress; `report` generates HTML from recorded evidence | | Deliver retained results | CLI `export --input --output [--agent-job]`; Python `apps.delivery.export_bundle` / `read_bundle` | Report-generating | Publishes Markdown, offline HTML, versioned result JSON and artifact index from one snapshot without remeasurement. Optional native-job input verifies standalone Benchmark terminal token usage. Iterative CLI final returns separate delivery status. See [result delivery](result-delivery.md) and [Benchmark metrics](../benchmarks/benchmark-metrics.md) | diff --git a/docs/guides/task-input.md b/docs/guides/task-input.md index a98469097..24c7e3cfb 100644 --- a/docs/guides/task-input.md +++ b/docs/guides/task-input.md @@ -10,6 +10,9 @@ without side effects. `inferrsi plan --task` and `inferrsi run --task` use a com file with the existing plan and run operations (see [use with plan and run](#use-with-plan-and-run)). +Intake confirmation records (`inferrsi task intake ...`) are a separate contract +used before a task file is complete; see [task intake](task-intake.md). + | Resource | Location | Print from an installed CLI | | --- | --- | --- | | JSON Schema (draft 2020-12) | `src/inferrsi/apps/cli/task-input/v1/schema.json` in the wheel | `inferrsi task schema` | diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md new file mode 100644 index 000000000..7124a3776 --- /dev/null +++ b/docs/guides/task-intake.md @@ -0,0 +1,144 @@ +# Task intake records (intake/v1) + +`intake/v1` is the confirmation record an Agent fills before a measured task. +A native question card, a numbered text fallback and an optional check-in +interview all write the same record; the record decides which fields still +block the next stage. It sits next to, not inside, the shared YAML task file +(`task-input/v1`, [task input](task-input.md)): the record states where each +value came from, and only fields mapped to `task-input/v1` are expected to +reach a task file. + +The contract is `inferrsi.apps.cli.intake_contract`; the commands are +`inferrsi task intake ...`. Nothing here starts a process, probes a device or +freezes a gate. `evaluate` and `answer` write only the `--record` file the caller names. + +## Files + +| File | Owner | +| --- | --- | +| `src/inferrsi/apps/cli/intake_contract.py` | Record validation, question selection, answers, summary; pure functions | +| `skill_library/tasks/task-performance/intake.json` | Field spec for a performance round | +| `skill_library/tasks/task-day-0/intake.json` | Day-zero fields; none map to `task-input/v1` | +| `src/inferrsi/apps/cli/task_intake.py` | Record file I/O and the commands | +| `tests/fixtures/intake/` | Complete, partial and frozen-gate fixtures | + +## Record + +```json +{ + "schema_version": 1, + "record_id": "intake-...", + "revision": 3, + "task": "task-performance", + "primary_task": {"value": "task-performance", "source": "prompt", "status": "confirmed"}, + "phase": "intake", + "fields": { + "acceptance.metric_key": {"value": "p95_ttft", "source": "issue", "status": "confirmed"}, + "protocol.comparison": {"value": null, "source": "answer:q:protocol.comparison", + "status": "unknown", "asked": true} + }, + "open_questions": [], + "blockers": [], + "conflicts": [], + "allowed_next": ["read_only_preparation", "baseline_measurement"], + "execution": "not started" +} +``` + +- `source` names where a value came from: `prompt`, `answer:`, + `task_file`, `issue`, `repo_inspection`, `derived`, `default`, + `grilling_brief`, `frozen_gate` or `unknown`. The caller declares it; InferRSI + records it and does not authenticate it. +- `status` is one of `confirmed`, `proposed`, `assumed`, `unknown`, + `conflicting`, `stale`, `superseded`. +- `allowed_next` is derived by `evaluate`; a caller never fills it by hand. + `service_execution` and `device_execution` never appear there: they need a + separate authorization. + +## Field specs + +Each primary task owns an `intake.json` next to its `SKILL.md`. A field declares: + +| Key | Meaning | +| --- | --- | +| `path` | Field path; `acceptance.*` paths carry the gate boundary | +| `maps_to` | `task-input/v1`, `campaign-protocol`, `session-protocol`, `summary-only` or `day0-spec` | +| `batch` | Question batch (1 = goal and gates, 2 = environment identity, 3 = protocol, scope and budget) | +| `type` | `text`, `number`, `integer` or `choice` | +| `question`, `options` | Card text and options; `{value, hint}` objects | +| `depends_on` | Fields that must be settled before this question applies | +| `required_when` | Conditional applicability, e.g. service reuse fields | +| `required_before` | Stages this field blocks while it is not settled | + +`task-day-0` fields map to `day0-spec` and stay in the record and the summary. +They do not enter a `task-input/v1` file, which rejects unknown keys. + +## Commands + +```text +inferrsi task intake evaluate --task task-performance --record \ + --set optimization.objective="reduce p95 TTFT" --source prompt [--json] +inferrsi task intake answer --record --question --value [--json] +inferrsi task intake answer --record --question --unknown [--json] +inferrsi task intake summary --record [--json] +``` + +`evaluate` creates the record when it does not exist, merges `--set` values, +writes the record back and prints the questions that unblock the next stage. +`answer` applies one recorded question, bumps the revision and re-evaluates. +`summary` reads without writing. + +Every command accepts `--frozen `: a schema-v1 task file whose +`acceptance` section is compared with the record, except `acceptance.reference`, +which names the gate record itself. A disagreement is reported as a conflict and +blocks candidate search. + +## Question selection + +1. A field is asked only when it applies (`depends_on` settled, `required_when` + satisfied), it is still `unknown` and it was never answered `unknown`. +2. A conflicting field is asked before anything else; its options are the + recorded candidate values with their sources. +3. Otherwise the lowest missing `batch` is asked as one batch. Answers to other + batches wait until earlier batches settle. +4. `unknown` is a recorded answer: the field is not asked again, and it blocks + every stage named in `required_before`. +5. Each question carries a dependency snapshot. An answer is rejected as + `stale_answer` when the snapshot changed, as `already_answered` when the same + question was answered once, and as `unknown_question` when it was never + issued. A late reply to a superseded question changes nothing. + +## Acceptance boundary + +A value for an `acceptance.*` field is `confirmed` only when the declared source +is `issue` or `frozen_gate`. A card answer, a prompt statement, a task file or an +interview brief is `proposed`. Proposed values do not unblock candidate search, +do not freeze a gate and do not override a value already confirmed by the +acceptance issue. A record that disagrees with the frozen gate record blocks +candidate search until the user resolves it. + +## Campaign hand-off + +```text +inferrsi campaign start ... --intake +``` + +`campaign start` evaluates the record for `task-performance` before writing any +plan. A blocked record prints the gate payload and exits `2`; nothing is +created. A ready record is written to `intake.json` in the campaign directory +and its sha256 is returned in the start result. Without `--intake`, start +prints a warning to stderr that the gate was not evaluated and proceeds as +before. + +The gate checks that the record is complete. It does not yet compare the record +with the campaign's own metric, quality and budget flags or with a frozen gate +file, and the digest is not part of `plan.json`; use `task intake evaluate +--frozen` for the gate comparison. + +## Cards and text fallback + +The runtime returns the same question objects to both presentations. A host may +render a native card; otherwise the Agent shows the same questions and options +as a numbered list. Both write answers through `task intake answer`, so the +normalized record is identical. Only the numbered text presentation has been +exercised so far; no host card adapter ships with this contract. diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index d039ebeff..7ad4dbf46 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -70,6 +70,28 @@ when the run requires it. During a frozen evaluation use the assigned entry and knowledge condition; keep the knowledge-off arm isolated. Setup, dashboard inspection and explicit evidence-ID lookups can use their own operations. +## Confirm the task-performance inputs + +Before any measurement, open the shared intake record with the fields the +request already states: + +```text +python -X utf8 "" task intake evaluate --task task-performance \ + --record --set = --source prompt +``` + +Ask the user only the questions it returns: use a native question card when +the host has one, otherwise show the same questions and options as a numbered +list. Record each answer with `task intake answer --record +--question --value ` (or `--unknown`) until `evaluate` reports +`complete: true`. A recorded card answer is a proposal: a threshold is +confirmed only by the acceptance issue or frozen plan. Pass `--frozen +` to compare the record with the frozen gate; a disagreement blocks +candidate search. While a field stays unknown, do only the stages listed in +`allowed_next`. Hand the complete record to `campaign start --intake +`; without it the campaign warns that the intake gate was not +evaluated. + ## Optimize an ordinary user project Default to the current Agent conversation. Read `campaign start --help` through diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index c76418009..97ec7ee37 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -345,9 +345,17 @@ def _context(records: list[dict]) -> str: def _task_command(args) -> int: - """Read one task file and print to stdout; no subprocess, probe or file write.""" + """Read one task file and print to stdout; no subprocess, probe or file write. + + ``task intake evaluate`` and ``answer`` are the exception: they also write the + caller-named ``--record`` file. They start no subprocess or probe either. + """ from . import task_input + if args.task_action == "intake": + from .task_intake import command as intake_command + + return intake_command(args) if args.task_action in ("schema", "template"): text = (task_input.schema_text() if args.task_action == "schema" else task_input.template_text()) @@ -862,7 +870,24 @@ def main(argv: list[str] | None = None) -> int: if getattr(args, "session_action", None) is not None: from ..delivery import after_final + gate = None + intake_record = getattr(args, "intake", None) + if args.session_action == "start" and getattr(args, "project_task", False): + from .task_intake import attach_record, campaign_gate + + if intake_record is not None: + gate, gated_record = campaign_gate(intake_record) + if gate["status"] != "ready": + _print(gate) + return 2 + else: + print( + "warning: no --intake record; the task-performance intake " + "gate was not evaluated", file=sys.stderr, + ) result = _optimization_session(args) + if gate is not None and Path(args.session).is_dir(): + result.update(attach_record(Path(args.session), gated_record, gate)) _print(after_final(args, result)) if "exit_code" in result: return result["exit_code"] diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index a46b86171..6376c3124 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -183,6 +183,9 @@ def _optimization_actions(stages, *, project=False): help="AB/BA (default), or one owned service per retained attempt") start.add_argument("--evaluation-config", type=Path, help="Explicit service-reuse JSON protocol (required in that mode)") + start.add_argument("--intake", type=Path, + help="intake/v1 record; the campaign refuses to start until it is " + "complete for the performance task") start.add_argument("--repo", type=Path, required=True) start.add_argument("--include", action="append", required=True, help="Project-relative input file/directory; repeat for dependencies") @@ -527,7 +530,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: child.add_argument("--dry-run", action="store_true") task = commands.add_parser( - "task", help="Read a YAML task file without starting or writing anything" + "task", help="Read a YAML task file, or keep an intake record; starts nothing" ) task_actions = task.add_subparsers(dest="task_action", required=True) for name, text in ( @@ -541,6 +544,37 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: _task_overrides(child) task_actions.add_parser("schema", help="Print the packaged task JSON Schema") task_actions.add_parser("template", help="Print the packaged task template") + intake_parser = task_actions.add_parser( + "intake", help="Evaluate or answer intake/v1 confirmation records before a measured task" + ) + intake_actions = intake_parser.add_subparsers(dest="intake_action", required=True) + evaluate = intake_actions.add_parser( + "evaluate", help="List the questions that unblock the next stage and persist the record" + ) + evaluate.add_argument("--task", help="Primary task id; required when the record is new") + evaluate.add_argument("--record", type=Path, required=True, help="intake/v1 record file") + evaluate.add_argument("--set", action="append", default=[], metavar="PATH=VALUE", + help="Fields the request already states; repeatable") + evaluate.add_argument("--source", default="prompt", + help="Where --set values came from (prompt, issue, task_file, ...)") + evaluate.add_argument("--frozen", type=Path, + help="Frozen gate task file; its acceptance fields are compared") + evaluate.add_argument("--json", action="store_true") + answer = intake_actions.add_parser( + "answer", help="Record one answer to an open question and re-evaluate") + answer.add_argument("--record", type=Path, required=True) + answer.add_argument("--question", required=True, help="Question id from evaluate") + choice = answer.add_mutually_exclusive_group(required=True) + choice.add_argument("--value", help="Chosen option value or free-form text") + choice.add_argument("--unknown", action="store_true", + help="Record as unknown; dependent stages stay blocked") + answer.add_argument("--frozen", type=Path) + answer.add_argument("--json", action="store_true") + summary = intake_actions.add_parser( + "summary", help="Readable confirmation summary with sources and next steps") + summary.add_argument("--record", type=Path, required=True) + summary.add_argument("--frozen", type=Path) + summary.add_argument("--json", action="store_true") for name in ("status", "report"): child = commands.add_parser( diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py new file mode 100644 index 000000000..2637fa7b9 --- /dev/null +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -0,0 +1,590 @@ +"""intake/v1: host-independent task intake records for missing-field confirmation. + +A card, a numbered text fallback and an optional check-in interview all write the +same record. The record separates what the user stated (``confirmed``), what a +card answer proposes (``proposed``), what stays unknown (``unknown``) and what +conflicts (``conflicting``). ``evaluate`` selects the questions that unblock the +next stage, derives ``allowed_next`` and never authenticates acceptance +thresholds: a proposal kept in a record does not freeze a gate. + +Nothing here performs I/O or imports another InferRSI module. Callers in +``inferrsi.apps.cli.task_intake`` load the versioned spec and record, then call these +pure functions. ``source`` is declared by the caller and is not authenticated. +""" + +from __future__ import annotations + +import copy +import json +import math + +SCHEMA_VERSION = 1 + +# Stage vocabulary. ``read_only_preparation`` is always allowed; the others are +# unlocked only when no field declared ``required_before`` that stage is missing. +STAGES = ( + "read_only_preparation", + "baseline_measurement", + "candidate_search", + "service_execution", + "device_execution", +) +BLOCKING_STAGES = STAGES[1:] + +# Where each field lands when a record is handed to an execution entry. +MAP_TARGETS = ("task-input/v1", "campaign-protocol", "session-protocol", + "summary-only", "day0-spec") + +STATUSES = ("confirmed", "proposed", "assumed", "unknown", "conflicting", + "stale", "superseded") +SETTLED = ("confirmed", "proposed", "assumed") +BLOCKING = ("unknown", "conflicting", "stale", "superseded") + +ACCEPTANCE = "acceptance." +# Sources whose values may confirm an acceptance threshold. Everything else, +# including card answers, stays a proposal until the acceptance issue or the +# frozen plan states it. +AUTHORITATIVE = ("issue", "frozen_gate") + +_QUESTION = "q:" + + +class IntakeError(ValueError): + """A record, spec or answer is rejected; ``code`` names the recorded reason.""" + + def __init__(self, code: str, message: str): + super().__init__(message) + self.code = code + + +def _canonical(value: object) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def _field_paths(spec: dict) -> dict[str, dict]: + return {field["path"]: field for field in spec["fields"]} + + +def validate_spec(spec: object) -> list[dict]: + """Return field-level problems in a packaged intake spec, in spec order.""" + problems: list[dict] = [] + + def bad(path: str, message: str) -> None: + problems.append({"field": path, "message": message}) + + if not isinstance(spec, dict): + return [{"field": "$", "message": "must be an object"}] + if spec.get("schema_version") != SCHEMA_VERSION: + bad("schema_version", f"must be {SCHEMA_VERSION}") + if not isinstance(spec.get("task"), str) or not spec["task"].strip(): + bad("task", "must be a non-empty string") + fields = spec.get("fields") + if not isinstance(fields, list) or not fields: + bad("fields", "must be a non-empty array") + return problems + seen: set[str] = set() + for index, field in enumerate(fields): + where = f"fields[{index}]" + if not isinstance(field, dict): + bad(where, "must be an object") + continue + path = field.get("path") + if not isinstance(path, str) or not path.strip(): + bad(f"{where}.path", "must be a non-empty string") + elif path in seen: + bad(f"{where}.path", f"duplicates {path}") + else: + seen.add(path) + if field.get("maps_to") not in MAP_TARGETS: + bad(f"{where}.maps_to", f"must be one of {', '.join(MAP_TARGETS)}") + if not isinstance(field.get("question"), str) or not field["question"].strip(): + bad(f"{where}.question", "must be a non-empty string") + batch = field.get("batch", 1) + if type(batch) is not int or batch < 1: + bad(f"{where}.batch", "must be a positive integer") + required = field.get("required_before", []) + if not isinstance(required, list) or any( + stage not in BLOCKING_STAGES for stage in required + ): + bad(f"{where}.required_before", + f"must list stages from {', '.join(BLOCKING_STAGES)}") + depends = field.get("depends_on", []) + if not isinstance(depends, list) or any(not isinstance(dep, str) for dep in depends): + bad(f"{where}.depends_on", "must be an array of field paths") + options = field.get("options", []) + if not isinstance(options, list) or any( + not isinstance(option, dict) or "value" not in option for option in options + ): + bad(f"{where}.options", "must be an array of {value, hint} objects") + when = field.get("required_when") + if when is not None and ( + not isinstance(when, dict) or not isinstance(when.get("field"), str) + or "equals" not in when + ): + bad(f"{where}.required_when", "must be {field, equals}") + for field in fields: + if not isinstance(field, dict): + continue + when = field.get("required_when") + if isinstance(when, dict) and when.get("field") not in seen: + bad(f"{field.get('path', '?')}.required_when", + f"names unknown field {when.get('field')}") + for dep in field.get("depends_on", []) if isinstance(field.get("depends_on"), list) else (): + if dep not in seen: + bad(f"{field.get('path', '?')}.depends_on", f"names unknown field {dep}") + return problems + + +def load_spec(spec: object) -> dict: + """Validate and return the spec; raise ``IntakeError('invalid_spec')``.""" + problems = validate_spec(spec) + if problems: + first = problems[0] + raise IntakeError("invalid_spec", f"{first['field']}: {first['message']}") + return spec + + +def new_record(task: str, *, record_id: str, primary_source: str = "prompt") -> dict: + """An empty intake record for ``task`` with a confirmed primary task.""" + return { + "schema_version": SCHEMA_VERSION, + "record_id": record_id, + "revision": 1, + "task": task, + "primary_task": {"value": task, "source": primary_source, "status": "confirmed"}, + "phase": "intake", + "fields": {}, + "open_questions": [], + "blockers": [], + "conflicts": [], + "allowed_next": ["read_only_preparation"], + "execution": "not started", + } + + +def validate_record(record: object, spec: dict) -> list[dict]: + """Return field-level problems in a record against its spec.""" + problems: list[dict] = [] + + def bad(field: str, message: str) -> None: + problems.append({"field": field, "message": message}) + + if not isinstance(record, dict): + return [{"field": "$", "message": "must be an object"}] + if record.get("schema_version") != SCHEMA_VERSION: + bad("schema_version", f"must be {SCHEMA_VERSION}") + if record.get("task") != spec["task"]: + bad("task", f"must equal the spec task {spec['task']}") + revision = record.get("revision") + if type(revision) is not int or revision < 1: + bad("revision", "must be a positive integer") + primary = record.get("primary_task") + if not isinstance(primary, dict) or primary.get("status") not in STATUSES: + bad("primary_task", "must carry a value, source and known status") + elif primary.get("value") != record.get("task"): + bad("primary_task.value", f"must be {record.get('task')}") + fields = record.get("fields") + if not isinstance(fields, dict): + bad("fields", "must be an object") + return problems + known = _field_paths(spec) + for path, entry in fields.items(): + if path not in known: + bad(path, "is not a field of this task spec") + continue + if not isinstance(entry, dict): + bad(path, "must be an object") + continue + if entry.get("status") not in STATUSES: + bad(path, f"status must be one of {', '.join(STATUSES)}") + if not isinstance(entry.get("source", "unknown"), str): + bad(path, "source must be a string") + if type(entry.get("asked", False)) is not bool: + bad(path, "asked must be a boolean") + return problems + + +def _check(record: dict, spec: dict) -> None: + problems = validate_record(record, spec) + if problems: + first = problems[0] + raise IntakeError("invalid_record", f"{first['field']}: {first['message']}") + + +def _entry(record: dict, path: str) -> dict: + return record["fields"].get(path) or {"value": None, "source": "unknown", + "status": "unknown", "asked": False} + + +def _settled(record: dict, path: str) -> bool: + return _entry(record, path).get("status") in SETTLED + + +def _coerce(field: dict, value: object) -> object: + kind = field.get("type", "text") + if kind == "number": + number = value + if isinstance(value, bool) or not isinstance(value, (int, float)): + number = None + if isinstance(value, str): + try: + number = float(value) + except ValueError: + number = None + if number is None or not math.isfinite(float(number)): + raise IntakeError("invalid_value", f"{field['path']} must be a finite number") + return float(number) + if kind == "integer": + if type(value) is int: + return value + if isinstance(value, str): + try: + return int(value) + except ValueError: + pass + raise IntakeError("invalid_value", f"{field['path']} must be an integer") + if kind == "choice": + allowed = [option["value"] for option in field.get("options", [])] + if value not in allowed: + raise IntakeError( + "invalid_value", f"{field['path']} must be one of {', '.join(allowed)}") + return value + if not isinstance(value, str) or not value.strip(): + raise IntakeError("invalid_value", f"{field['path']} must be a non-empty string") + return value + + +def _status_for(path: str, source: str) -> str: + if path.startswith(ACCEPTANCE) and source not in AUTHORITATIVE: + return "proposed" + return "confirmed" + + +def _bump(record: dict, next_revision: int) -> None: + record["revision"] = next_revision + + +def _rank(status: str) -> int: + return {"confirmed": 2, "proposed": 1}.get(status, 0) + + +def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: + """Merge stated values into a copy of ``record``; raise on invalid fields/values.""" + _check(record, spec) + if not isinstance(values, dict): + raise IntakeError("invalid_record", "values must be a mapping") + updated = copy.deepcopy(record) + fields = _field_paths(spec) + changed = False + revision = updated["revision"] + for path, raw in values.items(): + if path not in fields: + raise IntakeError("invalid_field", f"{path} is not a field of {spec['task']}") + value = _coerce(fields[path], raw) + status = _status_for(path, source) + current = updated["fields"].get(path) + if current is not None and not current.get("candidates") and ( + current.get("value") == value + ): + if _rank(status) <= _rank(current.get("status", "unknown")): + continue # same value, no stronger source: leave the record unchanged + updated["fields"][path] = {"value": value, "source": source, "status": status} + changed = True + continue + if (current is not None and current.get("status") == "conflicting" + and isinstance(current.get("candidates"), list)): + candidates = [item for item in current["candidates"] if item["value"] != value] + candidates.append({"value": value, "source": source}) + if len({_canonical(item["value"]) for item in candidates}) == 1: + updated["fields"][path] = {"value": value, "source": source, "status": status} + else: + updated["fields"][path] = {"value": None, "source": source, + "status": "conflicting", + "candidates": candidates} + changed = True + continue + if (current is not None and current.get("status") not in (None, "unknown") + and current.get("value") is not None and current.get("value") != value): + authoritative_new = source in AUTHORITATIVE + authoritative_old = current.get("source") in AUTHORITATIVE + if authoritative_new and not authoritative_old: + # The issue/task file settles a previously stated or proposed value. + updated["fields"][path] = {"value": value, "source": source, + "status": _status_for(path, source)} + changed = True + elif authoritative_old and not authoritative_new: + continue # the accepted value wins over a later proposal + else: + updated["fields"][path] = {"value": None, "source": source, + "status": "conflicting", + "candidates": [ + {"value": current["value"], + "source": current.get("source", "unknown")}, + {"value": value, "source": source}, + ]} + changed = True + continue + entry = {"value": value, "source": source, "status": status} + if current is not None and current.get("asked"): + entry["asked"] = True + updated["fields"][path] = entry + changed = True + if changed: + _bump(updated, revision + 1) + return updated + + +def set_primary_task(record: dict, spec: dict, *, value: str, source: str) -> dict: + """Change the selected primary task; open questions become stale by snapshot.""" + _check(record, spec) + if value != record["task"]: + raise IntakeError( + "invalid_primary_task", + f"record task is {record['task']}; a different primary task needs its own record", + ) + updated = copy.deepcopy(record) + if updated["primary_task"].get("source") != source: + updated["primary_task"] = {"value": value, "source": source, "status": "confirmed"} + _bump(updated, updated["revision"] + 1) + return updated + + +def _applicable(record: dict, field: dict) -> bool: + for dep in field.get("depends_on", []): + if not _settled(record, dep): + return False + when = field.get("required_when") + if isinstance(when, dict): + entry = _entry(record, when["field"]) + if entry.get("value") != when.get("equals"): + return False + return True + + +def _question(record: dict, spec: dict, field: dict) -> dict: + snapshot = {"__primary_task__": record["primary_task"]["value"]} + dependencies = list(field.get("depends_on", [])) + when = field.get("required_when") + if isinstance(when, dict): + dependencies.append(when["field"]) + for dep in dependencies: + snapshot[dep] = _entry(record, dep).get("value") + options = field.get("options", []) + entry = _entry(record, field["path"]) + if entry.get("status") == "conflicting" and isinstance(entry.get("candidates"), list): + options = [{"value": item["value"], "hint": f"from {item['source']}"} + for item in entry["candidates"]] + return { + "id": _QUESTION + field["path"], + "field": field["path"], + "batch": field.get("batch", 1), + "question": field["question"], + "options": options, + "fallback": "unknown", + "depends_on": snapshot, + } + + +def _frozen_conflicts(record: dict, spec: dict, frozen: dict | None) -> list[dict]: + if not frozen: + return [] + conflicts = [] + for field in spec["fields"]: + path = field["path"] + if not path.startswith(ACCEPTANCE) or path not in frozen: + continue + entry = _entry(record, path) + if entry.get("value") is None: + continue + if _canonical(entry["value"]) != _canonical(frozen[path]): + conflicts.append({ + "field": path, + "message": "record value disagrees with the frozen gate record", + "record_value": entry["value"], + "frozen_value": frozen[path], + }) + return conflicts + + +def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: + """Return the questions, blockers, conflicts and allowed next steps. + + Questions are the fields of the lowest missing ``batch`` that still apply; + a conflicting field is asked before anything else so the user can resolve + it. A field answered with ``unknown`` is not asked again: it blocks its + stage until a later source states it. + """ + _check(record, spec) + fields = _field_paths(spec) + conflicts = _frozen_conflicts(record, spec, frozen) + question_fields = [] + for field in spec["fields"]: + if not _applicable(record, field): + continue + entry = _entry(record, field["path"]) + if entry.get("status") == "conflicting": + question_fields.append(field) + if not question_fields: + missing = [] + for field in spec["fields"]: + if not _applicable(record, field): + continue + entry = _entry(record, field["path"]) + if entry.get("status") == "unknown" and not entry.get("asked"): + missing.append(field) + if missing: + lowest = min(field.get("batch", 1) for field in missing) + question_fields = [field for field in missing if field.get("batch", 1) == lowest] + questions = [_question(record, spec, field) for field in question_fields] + blockers = [] + for stage in BLOCKING_STAGES: + blocked_by = [] + for path, entry in ((path, _entry(record, path)) for path in fields): + field = fields[path] + if stage not in field.get("required_before", []): + continue + if not _applicable(record, field): + continue + status = entry.get("status") + if status in BLOCKING or ( + path.startswith(ACCEPTANCE) and status != "confirmed" + ): + blocked_by.append({"field": path, "status": status}) + if blocked_by: + blockers.append({"stage": stage, "blocked_by": blocked_by}) + if conflicts: + # A gate mismatch blocks candidate search even when every stated field + # is otherwise settled: the accepted record is no longer the same gate. + entries = [{"field": item["field"], "status": "conflicting"} for item in conflicts] + existing = next((item for item in blockers if item["stage"] == "candidate_search"), + None) + if existing is None: + blockers.append({"stage": "candidate_search", "blocked_by": entries}) + else: + existing["blocked_by"].extend(entries) + blocked_stages = {item["stage"] for item in blockers} + # Device and service execution always need a separate authorization; the + # record only unlocks preparation, baseline measurement and candidate search. + allowed_next = ["read_only_preparation"] + [ + stage for stage in ("baseline_measurement", "candidate_search") + if stage not in blocked_stages + ] + complete = not blockers and not conflicts + return { + "schema_version": SCHEMA_VERSION, + "task": spec["task"], + "record_id": record["record_id"], + "revision": record["revision"], + "phase": record["phase"], + "primary_task": record["primary_task"], + "questions": questions, + "blockers": blockers, + "conflicts": conflicts, + "allowed_next": allowed_next, + "complete": complete, + "execution": "not started", + "fields": { + path: {"value": entry.get("value"), "source": entry.get("source"), + "status": entry.get("status")} + for path, entry in record["fields"].items() + }, + } + + +def answer(record: dict, spec: dict, *, question_id: str, value: object = None, + unknown: bool = False) -> dict: + """Apply one answer to a copy of ``record``. + + The question must be one ``evaluate`` previously recorded in + ``record["open_questions"]``; its dependency snapshot must still hold and + the field must still be open. A duplicate, stale or inapplicable delivery + is rejected, so a late reply to a superseded question changes nothing. + """ + _check(record, spec) + open_questions = record.get("open_questions") + if not isinstance(open_questions, list): + raise IntakeError("invalid_record", + "open_questions must be recorded by evaluate before answering") + question = next((item for item in open_questions + if isinstance(item, dict) and item.get("id") == question_id), None) + if question is None: + answered = any(entry.get("source") == f"answer:{question_id}" + for entry in record["fields"].values()) + if answered: + raise IntakeError("already_answered", + f"{question_id} was already recorded; re-evaluate for " + "current questions") + named = question_id[len(_QUESTION):] if question_id.startswith(_QUESTION) else None + if named in _field_paths(spec): + raise IntakeError("stale_answer", + f"{question_id} is not open in the current record; re-evaluate") + raise IntakeError("unknown_question", + f"No recorded open question {question_id}; run evaluate first") + fields = _field_paths(spec) + field = fields.get(question.get("field")) + if field is None: + raise IntakeError("unknown_question", + f"{question_id} names a field outside {spec['task']}; re-evaluate") + snapshot = {"__primary_task__": record["primary_task"]["value"]} + dependencies = list(field.get("depends_on", [])) + when = field.get("required_when") + if isinstance(when, dict): + dependencies.append(when["field"]) + for dep in dependencies: + snapshot[dep] = _entry(record, dep).get("value") + if snapshot != question.get("depends_on"): + raise IntakeError("stale_answer", + f"{question_id} was asked before its dependencies changed; " + "re-evaluate") + if not _applicable(record, field) or _entry(record, field["path"]).get("status") not in ( + "unknown", "conflicting", + ): + raise IntakeError("stale_answer", + f"{question_id} no longer applies; re-evaluate") + updated = copy.deepcopy(record) + if unknown: + updated["fields"][field["path"]] = { + "value": None, "source": f"answer:{question_id}", + "status": "unknown", "asked": True, + } + _bump(updated, updated["revision"] + 1) + else: + updated = set_fields(updated, spec, {field["path"]: value}, + source=f"answer:{question_id}") + entry = updated["fields"][field["path"]] + entry["asked"] = True + updated["open_questions"] = [ + item for item in updated["open_questions"] if item.get("id") != question_id] + return updated + + +def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: + """A readable confirmation summary: sources, proposals, unknowns and next steps.""" + view = evaluate(record, spec, frozen=frozen) + confirmed, proposed, unknown = {}, {}, [] + for field in spec["fields"]: + path = field["path"] + entry = _entry(record, path) + status = entry.get("status") + if status == "confirmed": + confirmed[path] = entry.get("value") + elif status == "proposed": + proposed[path] = entry.get("value") + elif status in ("unknown", "conflicting", "stale", "superseded"): + unknown.append(path) + return { + "schema_version": SCHEMA_VERSION, + "task": spec["task"], + "record_id": record["record_id"], + "revision": record["revision"], + "primary_task": record["primary_task"], + "phase": record["phase"], + "confirmed": confirmed, + "proposed": proposed, + "unknown": unknown, + "conflicts": view["conflicts"], + "blockers": view["blockers"], + "allowed_next": view["allowed_next"], + "complete": view["complete"], + "execution": "not started", + } diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py new file mode 100644 index 000000000..f41efd6b4 --- /dev/null +++ b/src/inferrsi/apps/cli/task_intake.py @@ -0,0 +1,263 @@ +"""intake/v1 CLI: evaluate, answer and summarize confirmation records. + +The contract lives in ``inferrsi.apps.cli.intake_contract``. This module loads the +versioned per-task spec and the record file, applies the pure contract +functions and writes the record back. It starts nothing and measures nothing; +``execution`` stays ``not started`` until an existing operation is authorized. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +import uuid +from importlib.resources import files +from pathlib import Path + +from . import intake_contract as intake + + +def _spec_root() -> Path: + return Path(str(files("inferrsi").joinpath("knowledge", "data", "skill_library", "tasks"))) + + +def spec_path(task: str) -> Path: + return _spec_root() / task / "intake.json" + + +def load_spec(task: str) -> dict: + path = spec_path(task) + if not path.is_file(): + raise intake.IntakeError("unknown_task", f"No intake spec is packaged for {task}") + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise intake.IntakeError("invalid_spec", f"{task}/intake.json: {exc}") from exc + return intake.load_spec(data) + + +def read_record(path: Path) -> dict: + try: + raw = Path(path).read_text(encoding="utf-8") + except OSError as exc: + raise intake.IntakeError( + "unreadable_record", f"cannot read {path}: {exc.strerror or exc}") from exc + try: + record = json.loads(raw) + except json.JSONDecodeError as exc: + raise intake.IntakeError("invalid_record", f"{path}: {exc}") from exc + if not isinstance(record, dict): + raise intake.IntakeError("invalid_record", f"{path}: record must be an object") + return record + + +def _payload(record: dict) -> str: + return json.dumps(record, ensure_ascii=False, indent=2) + "\n" + + +def write_record(path: Path, record: dict) -> str: + """Write the record atomically; return the sha256 of the written bytes.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + text = _payload(record) + descriptor, temp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp") + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + stream.write(text) + os.replace(temp, path) + except BaseException: + Path(temp).unlink(missing_ok=True) + raise + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def frozen_values(path: Path) -> dict: + """Acceptance values stated by a frozen gate task file, keyed by spec path.""" + from . import task_input + + preview = task_input.preview(path) + if not preview["valid"]: + first = preview["errors"][0] + raise intake.IntakeError( + "invalid_frozen", f"frozen gate record: {first['field']} {first['message']}") + acceptance = preview["task"]["acceptance"] + # ``reference`` names the gate record itself and is path-normalized by the task + # contract, so it is not compared; ``task_input.frozen_gate`` makes the same choice. + return {f"acceptance.{name}": value for name, value in acceptance.items() + if value is not None and name != "reference"} + + +def parse_sets(items: list[str]) -> dict: + values = {} + for item in items: + path, separator, value = item.partition("=") + if not separator or not path.strip(): + raise intake.IntakeError("invalid_set", f"--set expects PATH=VALUE, got {item!r}") + values[path.strip()] = value + return values + + +def _persist(path: Path, record: dict, view: dict) -> None: + record["open_questions"] = view["questions"] + record["blockers"] = view["blockers"] + record["conflicts"] = view["conflicts"] + record["allowed_next"] = view["allowed_next"] + record["complete"] = view["complete"] + write_record(path, record) + + +def evaluate_command(args) -> dict: + record_path = Path(args.record) + if record_path.is_file(): + record = read_record(record_path) + else: + if not args.task: + raise intake.IntakeError( + "missing_task", "the record does not exist yet; pass --task") + record = intake.new_record(args.task, record_id="intake-" + uuid.uuid4().hex[:12]) + if args.task and args.task != record["task"]: + raise intake.IntakeError( + "task_mismatch", f"the record already records {record['task']}, not {args.task}") + spec = load_spec(record["task"]) + values = parse_sets(args.set) + if values: + record = intake.set_fields(record, spec, values, source=args.source) + frozen = frozen_values(args.frozen) if args.frozen else None + view = intake.evaluate(record, spec, frozen=frozen) + _persist(record_path, record, view) + return view + + +def answer_command(args) -> dict: + record_path = Path(args.record) + record = read_record(record_path) + spec = load_spec(record["task"]) + record = intake.answer(record, spec, question_id=args.question, + value=args.value, unknown=bool(args.unknown)) + frozen = frozen_values(args.frozen) if args.frozen else None + view = intake.evaluate(record, spec, frozen=frozen) + _persist(record_path, record, view) + return view + + +def summary_command(args) -> dict: + record = read_record(Path(args.record)) + spec = load_spec(record["task"]) + frozen = frozen_values(args.frozen) if args.frozen else None + return intake.summary(record, spec, frozen=frozen) + + +def campaign_gate(path: Path, *, expected_task: str = "task-performance", + frozen: dict | None = None) -> tuple[dict, dict]: + """Evaluate a record for ``campaign start``; return the gate and the record it read. + + Never starts or measures anything. The caller retains the returned record, so the + bytes kept next to the campaign are the ones this gate evaluated. + """ + record = read_record(Path(path)) + if record.get("task") != expected_task: + raise intake.IntakeError( + "task_mismatch", f"{path} records {record.get('task')}, not {expected_task}") + spec = load_spec(expected_task) + view = intake.evaluate(record, spec, frozen=frozen) + return { + "status": "ready" if view["complete"] else "blocked", + "task": expected_task, + "record": str(path), + "revision": record["revision"], + "complete": view["complete"], + "questions": view["questions"], + "blockers": view["blockers"], + "conflicts": view["conflicts"], + "allowed_next": view["allowed_next"], + "execution": "not started", + }, record + + +def attach_record(session_dir: Path, record: dict, gate: dict) -> dict: + """Retain the gated record in the campaign directory and name its digest.""" + digest = write_record(Path(session_dir) / "intake.json", record) + return {"intake": { + "record": "intake.json", + "task": record["task"], + "revision": record["revision"], + "sha256": digest, + "gate": gate["status"], + }} + + +def _render_questions(view: dict) -> list[str]: + lines = [] + if view["questions"]: + lines.append("questions:") + for question in view["questions"]: + lines.append(f" {question['id']} {question['question']}") + for option in question["options"]: + hint = f" ({option['hint']})" if option.get("hint") else "" + lines.append(f" - {option['value']}{hint}") + lines.append(" - unknown (record as unknown; dependent stages stay blocked)") + return lines + + +def render(view: dict) -> str: + lines = [f"task: {view['task']} revision: {view['revision']} " + f"complete: {'true' if view['complete'] else 'false'}"] + lines.extend(_render_questions(view)) + if view["conflicts"]: + lines.append("conflicts:") + for item in view["conflicts"]: + lines.append(f" {item['field']}: record {item.get('record_value')!r} vs " + f"frozen {item.get('frozen_value')!r}") + if view["blockers"]: + lines.append("blocked stages:") + for blocker in view["blockers"]: + fields = ", ".join( + f"{item['field']} ({item['status']})" for item in blocker["blocked_by"]) + lines.append(f" {blocker['stage']}: {fields}") + lines.append("allowed next: " + ", ".join(view["allowed_next"])) + return "\n".join(lines) + + +def render_summary(view: dict) -> str: + lines = [f"task: {view['task']} revision: {view['revision']} " + f"complete: {'true' if view['complete'] else 'false'}"] + for label, values in (("confirmed", view["confirmed"]), ("proposed", view["proposed"])): + if values: + lines.append(f"{label}:") + for path, value in values.items(): + lines.append(f" {path} = {json.dumps(value, ensure_ascii=False)}") + if view["unknown"]: + lines.append("unknown:") + lines.extend(f" {path}" for path in view["unknown"]) + if view["conflicts"]: + lines.append("conflicts:") + for item in view["conflicts"]: + lines.append(f" {item['field']}: record {item.get('record_value')!r} vs " + f"frozen {item.get('frozen_value')!r}") + if view["blockers"]: + lines.append("blocked stages:") + for blocker in view["blockers"]: + lines.append(f" {blocker['stage']}") + lines.append("allowed next: " + ", ".join(view["allowed_next"])) + return "\n".join(lines) + + +def command(args) -> int: + try: + if args.intake_action == "evaluate": + result = evaluate_command(args) + elif args.intake_action == "answer": + result = answer_command(args) + else: + result = summary_command(args) + except intake.IntakeError as exc: + print(json.dumps({"error": exc.code, "message": str(exc), "execution": "not started"}, + ensure_ascii=False, indent=2)) + return 2 + if getattr(args, "json", False): + print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False)) + else: + print(render_summary(result) if args.intake_action == "summary" else render(result)) + return 0 diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/inference-task-router/SKILL.md b/src/inferrsi/knowledge/data/skill_library/tasks/inference-task-router/SKILL.md index d7ff9c811..cc1db9035 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/inference-task-router/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/tasks/inference-task-router/SKILL.md @@ -43,6 +43,8 @@ metadata: Choose one primary skill by the requested deliverable. Load its full procedure before the first supporting evidence search. Record secondary tasks for follow-up. +When two primary skills remain plausible after reading the request, ask the user +which deliverable they want before loading either; do not guess a route. The route cards remain available to callers that consume the JSON summaries. | Primary skill | Choose it when | Route card | diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-day-0/intake.json b/src/inferrsi/knowledge/data/skill_library/tasks/task-day-0/intake.json new file mode 100644 index 000000000..d01200c5b --- /dev/null +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-day-0/intake.json @@ -0,0 +1,63 @@ +{ + "schema_version": 1, + "task": "task-day-0", + "description": "Confirmation fields for day-zero support of a new checkpoint or architecture. These fields have no task-input/v1 home; they stay in the intake record and the task summary until a later task-file version defines them.", + "fields": [ + { + "path": "day0.checkpoint", + "maps_to": "day0-spec", + "batch": 1, + "type": "text", + "question": "Which checkpoint or weights must the target engine load?", + "required_before": ["device_execution"] + }, + { + "path": "day0.tokenizer_or_processor", + "maps_to": "day0-spec", + "batch": 1, + "type": "text", + "question": "Which tokenizer or processor accompanies the checkpoint?", + "required_before": ["device_execution"] + }, + { + "path": "day0.target_engine_and_device", + "maps_to": "day0-spec", + "batch": 1, + "type": "text", + "question": "Which engine revision and target device must run the model?", + "required_before": ["device_execution"] + }, + { + "path": "day0.first_scope", + "maps_to": "day0-spec", + "batch": 1, + "type": "text", + "question": "Which modalities or features must the first supported scope cover?", + "required_before": ["device_execution"] + }, + { + "path": "day0.reference_implementation", + "maps_to": "day0-spec", + "batch": 2, + "type": "text", + "question": "Which reference implementation produces the expected outputs?", + "required_before": ["device_execution"] + }, + { + "path": "day0.replayable_inputs", + "maps_to": "day0-spec", + "batch": 2, + "type": "text", + "question": "Which replayable inputs and fixtures anchor the stage-by-stage comparison?", + "required_before": ["device_execution"] + }, + { + "path": "day0.consistency_criteria", + "maps_to": "day0-spec", + "batch": 2, + "type": "text", + "question": "Which numeric or output-consistency criteria define supported behavior per stage?", + "required_before": ["device_execution"] + } + ] +} diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md index 76b25ae7c..4e64038cf 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md @@ -39,7 +39,11 @@ checkpoint revision, engine and plugin versions, and the exact run script and flags. Attach the benchmark inputs, workload shape, dtype, reference or quality oracle, and the user's acceptance criteria. Write down the current diagnosis and its supporting observation, allowed search space, and remaining budget. -Mark missing fields as unknown and request the first one that affects a decision. +Mark missing fields as unknown and open the shared intake record +(`task intake evaluate --task task-performance`); ask only the questions it +returns. A field answered `unknown` blocks its stage instead of being asked +again. Do not derive a threshold from a request such as "make it faster": the +acceptance issue or frozen plan states it. ## Run the procedure diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json new file mode 100644 index 000000000..49166c712 --- /dev/null +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json @@ -0,0 +1,233 @@ +{ + "schema_version": 1, + "task": "task-performance", + "description": "Confirmation fields for a performance-optimization round. Questions are asked only for fields that block the next stage; acceptance values stated outside an acceptance issue or frozen task file stay proposals.", + "fields": [ + { + "path": "optimization.objective", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which outcome decides this round?", + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.metric_key", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which metric decides this round?", + "options": [ + {"value": "p95_ttft", "hint": "client-observed p95 time to first token"}, + {"value": "throughput", "hint": "requests completed per second under the fixed load"}, + {"value": "p95_tpot", "hint": "p95 time per output token"}, + {"value": "peak_memory", "hint": "peak device memory under the fixed load"} + ], + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.metric_unit", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which unit does the metric use?", + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.direction", + "maps_to": "task-input/v1", + "batch": 1, + "type": "choice", + "question": "Should the metric go down or up?", + "options": [ + {"value": "minimize", "hint": "lower is better"}, + {"value": "maximize", "hint": "higher is better"} + ], + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.min_improvement_pct", + "maps_to": "task-input/v1", + "batch": 1, + "type": "number", + "question": "What minimum improvement is required to keep a candidate?", + "depends_on": ["acceptance.metric_key"], + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.reference", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which acceptance issue or frozen plan states the gate?", + "required_before": ["candidate_search"] + }, + { + "path": "acceptance.baseline_revision", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which baseline revision is pinned for this round?", + "required_before": ["candidate_search"] + }, + { + "path": "environment.quality_command", + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which command checks output quality on a candidate?", + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_failure_policy", + "maps_to": "summary-only", + "batch": 1, + "type": "choice", + "question": "What happens when a candidate fails the quality check?", + "options": [ + {"value": "revert_candidate", "hint": "discard the candidate and keep the incumbent"}, + {"value": "keep_with_flag", "hint": "retain the candidate but flag the quality gap"} + ], + "required_before": ["candidate_search"] + }, + { + "path": "protocol.timing_boundary", + "maps_to": "summary-only", + "batch": 1, + "type": "text", + "question": "Where is the timing boundary, and does it include queueing or transfer?", + "required_before": ["baseline_measurement"] + }, + { + "path": "optimization.repository", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which prepared repository is the baseline checkout?", + "required_before": ["baseline_measurement"] + }, + { + "path": "optimization.model", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which model identity or path does the run load?", + "required_before": ["baseline_measurement"] + }, + { + "path": "optimization.model_revision", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which model revision is pinned?", + "required_before": ["candidate_search"] + }, + { + "path": "optimization.framework", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which engine or framework serves the model?", + "required_before": ["baseline_measurement"] + }, + { + "path": "environment.backend", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which backend runs the workload?", + "required_before": ["baseline_measurement"] + }, + { + "path": "environment.device_model", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which device SKU or chip must the measurement use?", + "required_before": ["baseline_measurement"] + }, + { + "path": "optimization.workload", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which fixed workload, input set and concurrency replay for every trial?", + "required_before": ["baseline_measurement"] + }, + { + "path": "environment.baseline_command", + "maps_to": "task-input/v1", + "batch": 2, + "type": "text", + "question": "Which command runs the unchanged baseline?", + "required_before": ["baseline_measurement"] + }, + { + "path": "environment.repetitions", + "maps_to": "task-input/v1", + "batch": 2, + "type": "integer", + "question": "How many repetitions and warmups should each side run?", + "required_before": ["baseline_measurement"] + }, + { + "path": "environment.max_minutes", + "maps_to": "task-input/v1", + "batch": 2, + "type": "number", + "question": "What time budget bounds the whole round?", + "required_before": ["baseline_measurement"] + }, + { + "path": "protocol.comparison", + "maps_to": "campaign-protocol", + "batch": 3, + "type": "choice", + "question": "How should baseline and candidate trials be compared?", + "options": [ + {"value": "abba", "hint": "alternate unchanged baseline and candidate under the same conditions"}, + {"value": "service_reuse", "hint": "keep one owned service and reuse it across retained candidates"} + ], + "required_before": ["candidate_search"] + }, + { + "path": "protocol.service_lifecycle", + "maps_to": "summary-only", + "batch": 3, + "type": "text", + "question": "When is the reused service restarted, and which caches or state are cleared between candidates?", + "depends_on": ["protocol.comparison"], + "required_when": {"field": "protocol.comparison", "equals": "service_reuse"}, + "required_before": ["candidate_search"] + }, + { + "path": "environment.candidate_command", + "maps_to": "task-input/v1", + "batch": 3, + "type": "text", + "question": "Which command runs a submitted candidate under the same conditions?", + "required_before": ["candidate_search"] + }, + { + "path": "optimization.plane", + "maps_to": "task-input/v1", + "batch": 3, + "type": "choice", + "question": "Which SIAS plane may this round change?", + "options": [ + {"value": "harness", "hint": "scheduling, batching, serving policy or harness code"}, + {"value": "model", "hint": "model execution, kernels or precision"}, + {"value": "infra", "hint": "runtime, drivers or device placement"} + ], + "required_before": ["candidate_search"] + }, + { + "path": "environment.rounds", + "maps_to": "task-input/v1", + "batch": 3, + "type": "integer", + "question": "How many candidate rounds may search run, and how much time is reserved for the final?", + "required_before": ["candidate_search"] + } + ] +} diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py new file mode 100644 index 000000000..d03ad75b7 --- /dev/null +++ b/tests/apps/test_task_intake.py @@ -0,0 +1,372 @@ +"""intake/v1: spec validation, question selection, answers, conflicts and the campaign gate.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from inferrsi.apps import cli +from inferrsi.apps.cli import intake_contract as intake +from inferrsi.apps.cli import task_intake +from tests.apps.test_project_optimization import project, start_arguments # noqa: F401 + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "intake" +PERFORMANCE = FIXTURES / "performance" +COMPLETE = json.loads((PERFORMANCE / "complete.json").read_text(encoding="utf-8")) +PARTIAL = json.loads((PERFORMANCE / "partial.json").read_text(encoding="utf-8")) +ALL_VALUES = {**COMPLETE["fields"]["values"], **COMPLETE["acceptance"]["values"]} + + +def spec_for(task: str = "task-performance") -> dict: + return task_intake.load_spec(task) + + +def build(paths: set[str] | None = None, *, task: str = "task-performance") -> dict: + """A record built from the complete fixture, optionally restricted to ``paths``.""" + spec = spec_for(task) + record = intake.new_record(task, record_id="intake-test") + if task == "task-performance": + chosen = {path: value for path, value in ALL_VALUES.items() + if paths is None or path in paths} + stated = {path: value for path, value in chosen.items() + if not path.startswith("acceptance.")} + accepted = {path: value for path, value in chosen.items() + if path.startswith("acceptance.")} + if stated: + record = intake.set_fields(record, spec, stated, source="prompt") + if accepted: + record = intake.set_fields(record, spec, accepted, source="issue") + return record + + +def ask(record: dict, spec: dict, frozen: dict | None = None) -> tuple[dict, dict]: + """Evaluate and persist the open questions, as the CLI does.""" + view = intake.evaluate(record, spec, frozen=frozen) + record = json.loads(json.dumps(record)) + record["open_questions"] = view["questions"] + return record, view + + +def batch_paths(spec: dict, batch: int) -> set[str]: + return {field["path"] for field in spec["fields"] if field.get("batch", 1) == batch} + + +def test_packaged_specs_validate_and_declare_their_targets(): + for task in ("task-performance", "task-day-0"): + spec = spec_for(task) + assert spec["task"] == task + assert intake.validate_spec(spec) == [] + assert all(field["maps_to"] in intake.MAP_TARGETS for field in spec["fields"]) + + +def test_day0_fields_stay_out_of_task_input_v1(): + spec = spec_for("task-day-0") + assert all(field["maps_to"] == "day0-spec" for field in spec["fields"]) + + +def test_complete_record_asks_nothing_and_unlocks_search(): + spec = spec_for() + view = intake.evaluate(build(), spec) + assert view["complete"] is True + assert view["questions"] == [] + assert view["conflicts"] == [] + assert view["allowed_next"] == [ + "read_only_preparation", "baseline_measurement", "candidate_search"] + assert view["execution"] == "not started" + + +def test_empty_record_asks_only_the_first_batch(): + spec = spec_for() + view = intake.evaluate(intake.new_record("task-performance", record_id="intake-empty"), spec) + asked = {question["field"] for question in view["questions"]} + expected = batch_paths(spec, 1) - {"acceptance.min_improvement_pct"} + assert asked == expected + assert all(question["batch"] == 1 for question in view["questions"]) + assert view["complete"] is False + + +def test_second_batch_appears_once_the_first_is_settled(): + spec = spec_for() + record = build(batch_paths(spec, 1)) + view = intake.evaluate(record, spec) + asked = {question["field"] for question in view["questions"]} + assert asked == batch_paths(spec, 2) + assert all(question["batch"] == 2 for question in view["questions"]) + + +def test_unknown_answer_blocks_its_stage_and_is_not_asked_again(): + spec = spec_for() + record, view = ask(intake.new_record("task-performance", record_id="intake-unknown"), spec) + question = next(item for item in view["questions"] + if item["field"] == "protocol.timing_boundary") + record = intake.answer(record, spec, question_id=question["id"], unknown=True) + view = intake.evaluate(record, spec) + assert question["id"] not in {item["id"] for item in view["questions"]} + baseline = next(item for item in view["blockers"] + if item["stage"] == "baseline_measurement") + assert "protocol.timing_boundary" in {item["field"] for item in baseline["blocked_by"]} + assert view["allowed_next"] == ["read_only_preparation"] + assert record["fields"]["protocol.timing_boundary"] == { + "value": None, "source": f"answer:{question['id']}", + "status": "unknown", "asked": True, + } + + +def test_stale_answer_after_a_dependency_change_is_rejected(): + spec = spec_for() + record = build({"acceptance.metric_key"}) + record, view = ask(record, spec) + question = next(item for item in view["questions"] + if item["field"] == "acceptance.min_improvement_pct") + changed = intake.set_fields(record, spec, {"acceptance.metric_key": "p99_ttft"}, + source="issue") + with pytest.raises(intake.IntakeError) as error: + intake.answer(changed, spec, question_id=question["id"], value=5) + assert error.value.code == "stale_answer" + + +def test_duplicate_answer_is_rejected_once(): + spec = spec_for() + record, view = ask(intake.new_record("task-performance", record_id="intake-dup"), spec) + question = next(item for item in view["questions"] + if item["field"] == "acceptance.metric_key") + record = intake.answer(record, spec, question_id=question["id"], value="p95_ttft") + with pytest.raises(intake.IntakeError) as error: + intake.answer(record, spec, question_id=question["id"], value="p95_ttft") + assert error.value.code == "already_answered" + + +def test_acceptance_answer_from_a_card_stays_a_proposal(): + spec = spec_for() + record, view = ask(intake.new_record("task-performance", record_id="intake-card"), spec) + question = next(item for item in view["questions"] + if item["field"] == "acceptance.metric_key") + record = intake.answer(record, spec, question_id=question["id"], value="p95_ttft") + assert record["fields"]["acceptance.metric_key"]["status"] == "proposed" + view = intake.evaluate(record, spec) + search = next(item for item in view["blockers"] if item["stage"] == "candidate_search") + assert "acceptance.metric_key" in {item["field"] for item in search["blocked_by"]} + assert "candidate_search" not in view["allowed_next"] + summary = intake.summary(record, spec) + assert summary["proposed"]["acceptance.metric_key"] == "p95_ttft" + + +def test_acceptance_issue_confirms_a_previously_proposed_value(): + spec = spec_for() + record = intake.new_record("task-performance", record_id="intake-upgrade") + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, + source="prompt") + assert record["fields"]["acceptance.metric_key"]["status"] == "proposed" + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, + source="issue") + assert record["fields"]["acceptance.metric_key"]["status"] == "confirmed" + + +def test_two_stated_values_become_a_question_with_both_options(): + spec = spec_for() + record = intake.new_record("task-performance", record_id="intake-conflict") + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, + source="prompt") + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p99_ttft"}, + source="prompt") + assert record["fields"]["acceptance.metric_key"]["status"] == "conflicting" + record, view = ask(record, spec) + question = view["questions"][0] + assert question["field"] == "acceptance.metric_key" + values = {option["value"] for option in question["options"]} + assert values == {"p95_ttft", "p99_ttft"} + + +def test_frozen_gate_mismatch_blocks_candidate_search(): + spec = spec_for() + frozen = {"acceptance.metric_key": "p99_ttft"} + view = intake.evaluate(build(), spec, frozen=frozen) + assert view["complete"] is False + assert [item["field"] for item in view["conflicts"]] == ["acceptance.metric_key"] + search = next(item for item in view["blockers"] if item["stage"] == "candidate_search") + assert "acceptance.metric_key" in {item["field"] for item in search["blocked_by"]} + assert "candidate_search" not in view["allowed_next"] + + +def test_unknown_paths_are_rejected_by_the_record_check(): + spec = spec_for() + record = build() + record["fields"]["bogus.path"] = {"value": 1, "source": "prompt", "status": "confirmed"} + with pytest.raises(intake.IntakeError) as error: + intake.evaluate(record, spec) + assert error.value.code == "invalid_record" + + +def test_non_finite_numbers_are_rejected(): + spec = spec_for() + record = intake.new_record("task-performance", record_id="intake-nan") + with pytest.raises(intake.IntakeError) as error: + intake.set_fields(record, spec, {"acceptance.min_improvement_pct": "nan"}, + source="issue") + assert error.value.code == "invalid_value" + + +def test_cli_evaluate_matches_the_python_view_and_writes_only_the_record(tmp_path, capsys): + record_path = tmp_path / "record.json" + code = cli.main([ + "task", "intake", "evaluate", "--task", "task-performance", + "--record", str(record_path), "--json", + ]) + assert code == 0 + result = json.loads(capsys.readouterr().out) + stored = json.loads(record_path.read_text(encoding="utf-8")) + expected = intake.evaluate(stored, spec_for()) + for key in ("questions", "blockers", "conflicts", "allowed_next", "complete", + "execution", "revision"): + assert result[key] == expected[key] + assert {path.name for path in tmp_path.iterdir()} == {"record.json"} + + +def test_cli_answer_then_summary(tmp_path, capsys): + record_path = tmp_path / "record.json" + assert cli.main([ + "task", "intake", "evaluate", "--task", "task-performance", + "--record", str(record_path), "--set", "acceptance.metric_key=p95_ttft", "--json", + ]) == 0 + view = json.loads(capsys.readouterr().out) + question = next(item for item in view["questions"] + if item["field"] == "acceptance.metric_unit") + assert cli.main([ + "task", "intake", "answer", "--record", str(record_path), + "--question", question["id"], "--value", "ms", "--json", + ]) == 0 + capsys.readouterr() + assert cli.main(["task", "intake", "summary", "--record", str(record_path), + "--json"]) == 0 + summary = json.loads(capsys.readouterr().out) + assert summary["proposed"]["acceptance.metric_unit"] == "ms" + assert summary["execution"] == "not started" + + +def test_cli_stale_answer_exits_two(tmp_path, capsys): + record_path = tmp_path / "record.json" + assert cli.main([ + "task", "intake", "evaluate", "--task", "task-performance", + "--record", str(record_path), "--set", "acceptance.metric_key=p95_ttft", "--json", + ]) == 0 + view = json.loads(capsys.readouterr().out) + question = next(item for item in view["questions"] + if item["field"] == "acceptance.min_improvement_pct") + assert cli.main(["task", "intake", "evaluate", "--record", str(record_path), + "--set", "acceptance.metric_key=p99_ttft", "--json"]) == 0 + capsys.readouterr() + assert cli.main(["task", "intake", "answer", "--record", str(record_path), + "--question", question["id"], "--value", "5", "--json"]) == 2 + error = json.loads(capsys.readouterr().out) + assert error["error"] in ("stale_answer", "already_answered") + + +def test_frozen_values_read_the_gate_task_file(): + values = task_intake.frozen_values(PERFORMANCE / "frozen-gate.yaml") + assert values["acceptance.metric_key"] == "p95_ttft" + assert values["acceptance.min_improvement_pct"] == 10.0 + assert "acceptance.reference" not in values # names the record; never compared + + +def test_matching_frozen_gate_keeps_a_complete_record_complete(): + frozen = task_intake.frozen_values(PERFORMANCE / "frozen-gate.yaml") + view = intake.evaluate(build(), spec_for(), frozen=frozen) + assert view["conflicts"] == [] and view["complete"] is True + + +@pytest.mark.parametrize("source", ["prompt", "task_file", "grilling_brief", "repo_inspection"]) +def test_only_the_issue_or_frozen_record_confirms_an_acceptance_value(source): + spec = spec_for() + record = intake.new_record("task-performance", record_id="intake-source") + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, source=source) + assert record["fields"]["acceptance.metric_key"]["status"] == "proposed" + + +def test_campaign_gate_blocks_until_complete(tmp_path): + partial = tmp_path / "partial.json" + partial.write_text(json.dumps(build(set(PARTIAL["fields"]["values"]))), encoding="utf-8") + gate, _ = task_intake.campaign_gate(partial) + assert gate["status"] == "blocked" + assert gate["allowed_next"] == ["read_only_preparation"] + complete = tmp_path / "complete.json" + complete.write_text(json.dumps(build()), encoding="utf-8") + gate, gated = task_intake.campaign_gate(complete) + assert gate["status"] == "ready" + assert gate["complete"] is True + assert gated == build() + + +def test_campaign_start_refuses_an_incomplete_record_before_writing(project, tmp_path, capsys): # noqa: F811 + record = tmp_path / "record.json" + record.write_text(json.dumps(build(set(PARTIAL["fields"]["values"]))), encoding="utf-8") + assert cli.main(start_arguments(project, extra=("--intake", str(record)))) == 2 + gate = json.loads(capsys.readouterr().out) + assert gate["status"] == "blocked" and gate["execution"] == "not started" + assert not project[3].exists() + + +def test_campaign_start_retains_the_record_it_gated(project, tmp_path, capsys): # noqa: F811 + record = tmp_path / "record.json" + record.write_text(json.dumps(build()), encoding="utf-8") + assert cli.main(start_arguments(project, extra=("--intake", str(record)))) == 0 + result = json.loads(capsys.readouterr().out) + retained = project[3] / "intake.json" + assert result["intake"]["gate"] == "ready" + assert result["intake"]["sha256"] == hashlib.sha256(retained.read_bytes()).hexdigest() + assert json.loads(retained.read_text(encoding="utf-8")) == build() + # The retained record does not disturb the managed campaign's own records. + assert cli.main(["campaign", "status", "--directory", str(project[3])]) == 0 + + +def test_campaign_start_without_a_record_warns_and_proceeds(project, capsys): # noqa: F811 + assert cli.main(start_arguments(project)) == 0 + captured = capsys.readouterr() + assert "intake gate was not evaluated" in captured.err + assert "intake" not in json.loads(captured.out) + + +def test_day0_blocks_only_device_execution(): + spec = spec_for("task-day-0") + view = intake.evaluate(intake.new_record("task-day-0", record_id="intake-day0"), spec) + stages = {item["stage"] for item in view["blockers"]} + assert stages == {"device_execution"} + assert "device_execution" not in view["allowed_next"] + record = intake.new_record("task-day-0", record_id="intake-day0") + record = intake.set_fields(record, spec, { + "day0.checkpoint": "checkpoints/model-v1", + "day0.tokenizer_or_processor": "tokenizer-v1", + "day0.target_engine_and_device": "engine x.y on device Z", + "day0.first_scope": "text generation", + "day0.reference_implementation": "reference wheel 1.0", + "day0.replayable_inputs": "fixtures/day0-inputs", + "day0.consistency_criteria": "top-1 token agreement >= 99%", + }, source="prompt") + view = intake.evaluate(record, spec) + assert view["complete"] is True + assert "device_execution" not in view["allowed_next"] + + +def test_partial_fixture_asks_only_the_remaining_first_batch(): + spec = spec_for() + record = build(set(PARTIAL["fields"]["values"])) + view = intake.evaluate(record, spec) + asked = {question["field"] for question in view["questions"]} + assert "optimization.objective" not in asked + assert "protocol.timing_boundary" not in asked + assert "acceptance.metric_key" in asked + + +def test_frozen_conflict_via_cli(tmp_path, capsys): + record_path = tmp_path / "complete.json" + record_path.write_text(json.dumps(build()), encoding="utf-8") + assert cli.main([ + "task", "intake", "evaluate", "--record", str(record_path), + "--frozen", str(PERFORMANCE / "frozen-mismatch.yaml"), "--json", + ]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["complete"] is False + assert result["conflicts"][0]["field"] == "acceptance.metric_key" + assert result["conflicts"][0]["frozen_value"] == "p99_ttft" diff --git a/tests/fixtures/intake/performance/complete.json b/tests/fixtures/intake/performance/complete.json new file mode 100644 index 000000000..f699717bf --- /dev/null +++ b/tests/fixtures/intake/performance/complete.json @@ -0,0 +1,38 @@ +{ + "task": "task-performance", + "description": "A complete task-performance intake record: every field the spec asks for is stated, so evaluate returns no questions.", + "fields": { + "source": "prompt", + "values": { + "optimization.objective": "reduce p95 TTFT for the fixed decode workload", + "optimization.repository": ".", + "optimization.model": "", + "optimization.model_revision": "", + "optimization.framework": "vllm", + "optimization.workload": "fixed-prompts-v1, concurrency 8", + "optimization.plane": "harness", + "environment.backend": "cuda", + "environment.device_model": "", + "environment.baseline_command": "python bench.py --engine baseline {result}", + "environment.candidate_command": "python bench.py --engine candidate {result}", + "environment.quality_command": "python quality.py {candidate} {result}", + "environment.repetitions": 5, + "environment.max_minutes": 120, + "environment.rounds": 4, + "protocol.timing_boundary": "server-side, includes queueing but not client transfer", + "protocol.comparison": "abba", + "protocol.quality_failure_policy": "revert_candidate" + } + }, + "acceptance": { + "source": "issue", + "values": { + "acceptance.metric_key": "p95_ttft", + "acceptance.metric_unit": "ms", + "acceptance.direction": "minimize", + "acceptance.min_improvement_pct": 10, + "acceptance.reference": "plan/acceptance.md", + "acceptance.baseline_revision": "" + } + } +} diff --git a/tests/fixtures/intake/performance/frozen-gate.yaml b/tests/fixtures/intake/performance/frozen-gate.yaml new file mode 100644 index 000000000..ab8583562 --- /dev/null +++ b/tests/fixtures/intake/performance/frozen-gate.yaml @@ -0,0 +1,8 @@ +schema_version: 1 +acceptance: + metric_key: p95_ttft + metric_unit: ms + direction: minimize + min_improvement_pct: 10 + reference: plan/acceptance.md + baseline_revision: "" diff --git a/tests/fixtures/intake/performance/frozen-mismatch.yaml b/tests/fixtures/intake/performance/frozen-mismatch.yaml new file mode 100644 index 000000000..eb2cd9140 --- /dev/null +++ b/tests/fixtures/intake/performance/frozen-mismatch.yaml @@ -0,0 +1,8 @@ +schema_version: 1 +acceptance: + metric_key: p99_ttft + metric_unit: ms + direction: minimize + min_improvement_pct: 10 + reference: plan/acceptance.md + baseline_revision: "" diff --git a/tests/fixtures/intake/performance/partial.json b/tests/fixtures/intake/performance/partial.json new file mode 100644 index 000000000..c45db1c25 --- /dev/null +++ b/tests/fixtures/intake/performance/partial.json @@ -0,0 +1,15 @@ +{ + "task": "task-performance", + "description": "A partial task-performance intake record: only the goal and timing boundary are stated, so evaluate asks the remaining first-batch questions only.", + "fields": { + "source": "prompt", + "values": { + "optimization.objective": "make the existing service faster without losing quality", + "protocol.timing_boundary": "server-side, includes queueing but not client transfer" + } + }, + "acceptance": { + "source": "issue", + "values": {} + } +} From ef72c20017280bcd18908103df21b51e6b7ad96c Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 11:06:26 +0800 Subject: [PATCH 02/26] Refresh generated skill indexes for task intake Agent-assisted-by: Claude Code / claude-fable-5-2 [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/searchspace-index.json | 2 +- docs/skill-coverage.md | 2 +- .../data/skill_library/_compiled/_provenance.json | 2 +- .../knowledge/data/skill_library/_compiled/inputs.json | 8 +++++--- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index d5eefeacc..63aa49540 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -6,7 +6,7 @@ "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "f4399276c8389f33ad81a2a25ccd0ff4392a37635ae9c53943ece4995c84d246" + "metadata_sha256": "047e0ff9e089594c2dce41952fccb630218b80b192033545a5fad6871e419646" }, "skills": { "ascend-aclgraph-capture-replay": {"path": "systems/platforms/ascend/ascend-aclgraph-capture-replay/SKILL.md", "state": "covered", "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], ["Accelerator", "Optimize"], ["Accelerator", "Verify"]]}, diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index 4d92f1500..e8851159e 100644 --- a/docs/skill-coverage.md +++ b/docs/skill-coverage.md @@ -4,7 +4,7 @@ Generated from the registry, SKILL.md frontmatter and the two maintained matrices. **Do not edit by hand**; regenerate after any registry, skill, matrix or frozen-plan change. -- Input digest: `sha256:b1f3b477729a45ae923a5365d905c2715c5aac9d08a09d2dde92017c7aea2a09` +- Input digest: `sha256:dd49b8b1cd3b96e43a7f60e5b7ca2273be1d96d8dc835196fe6f249611e62551` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 3abf1a04e..3b53ca7a5 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "bf14fec0bd909efcfeb2bc02d69fe227d0c51ce6", + "source_revision": "c69930dfdba3cdaba28b0f7f18abd7a1b9a702e3", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index 93037ddac..8be71ce19 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -614,7 +614,7 @@ "description": "Select the starting route for day-0 model support, inference performance optimization, debugging, accuracy repair, version alignment, derived-engine development or independent runtime bring-up." }, "files": { - "SKILL.md": "3dae791f61b26810332e05fbabe6fd7113abf9ed8609aef663535a267525849c", + "SKILL.md": "ea7b823fd4b4e00531356649ef0963854a93cf958db2880efdceec870d6f0c5c", "references/routes/accuracy.json": "5a672842ec26262d8827f7ce8d92de9bd956859ff5244189c0519b8f0dd188e3", "references/routes/day0-model.json": "77b26d1300e5535d8b595cef95c6c803ea1322e92f38b68ae2905f69355a814f", "references/routes/debug.json": "75241e43d12fb961d3f48d1b683e4df321c0f18e683959aedca9722e78a8b78f", @@ -1168,7 +1168,8 @@ "description": "Use for Day-0 onboarding of a new checkpoint or architecture to a named inference engine. Produce a reproducible target run, stage parity evidence and a regression fixture." }, "files": { - "SKILL.md": "ca187de2205b3aa86b4ca5123fb0107a8235aa84f9d942d3771a8a665df1a0a3" + "SKILL.md": "ca187de2205b3aa86b4ca5123fb0107a8235aa84f9d942d3771a8a665df1a0a3", + "intake.json": "14ebe6f94888b17a06970ac7729ebd14f19c73c2de50ee16100c6eced85b0bbc" } }, "task-debug": { @@ -1204,7 +1205,8 @@ "description": "Use when a correct inference baseline misses a latency, throughput, memory or cost target. Compare compatible changes under the user's workload and quality gate." }, "files": { - "SKILL.md": "bf5a137504566b6ee4eeaee18400d52aae99a1db3c8247dea7247d653103df0b" + "SKILL.md": "29051a9dfbca6591374e715d8021f5af9748532baf1da1c7c49f4a0319653eda", + "intake.json": "6bc9a33c6c6da11d91686a135b7dd59017333851af3f563732ba5d901198e8d3" } }, "task-version-alignment": { From d5a8fa1d33d3524581f17c68716752fc7c08ccd2 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 11:09:45 +0800 Subject: [PATCH 03/26] Check both task intake specs in the installed wheel Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- tests/repository/check_installed.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 99c3055d9..2ec27c105 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -609,7 +609,9 @@ def _inventory(root, prefix): **_inventory(files("inferrsi").joinpath("knowledge", "data"), "knowledge/data"), **_inventory(files("inferrsi").joinpath("harness", "data"), "harness/data"), } -assert len(inventory) == 775, f"installed resource count is {len(inventory)}, expected 775" +assert len(inventory) == 777, f"installed resource count is {len(inventory)}, expected 777" +for task in ("task-day-0", "task-performance"): + assert f"knowledge/data/skill_library/tasks/{task}/intake.json" in inventory for name in inventory: if "/skill_library/" in name and name.endswith("/SKILL.md"): assert name.removesuffix("SKILL.md") + "metadata.json" not in inventory, name From 9bbbf4edf45a0d793c969f9bc9d85d901f7c22e5 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 11:47:28 +0800 Subject: [PATCH 04/26] Require user-selected performance criteria before measured work Keep workspace choices as suggestions, ask outstanding questions through the desktop host, and bind acceptance values to an independently selected issue or frozen snapshot. Re-evaluate existing intake records at campaign start. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 54 +++++-- plugins/inferrsi/skills/inferrsi/SKILL.md | 38 +++-- src/inferrsi/apps/cli/arguments.py | 3 +- src/inferrsi/apps/cli/intake_contract.py | 145 +++++++++++++----- src/inferrsi/apps/cli/task_intake.py | 58 +++++-- .../tasks/task-performance/SKILL.md | 11 ++ .../tasks/task-performance/intake.json | 15 +- tests/apps/test_task_intake.py | 120 ++++++++++++++- .../fixtures/intake/performance/complete.json | 2 +- 9 files changed, 354 insertions(+), 92 deletions(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 7124a3776..4f78c5f38 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -33,7 +33,9 @@ freezes a gate. `evaluate` and `answer` write only the `--record` file the calle "primary_task": {"value": "task-performance", "source": "prompt", "status": "confirmed"}, "phase": "intake", "fields": { - "acceptance.metric_key": {"value": "p95_ttft", "source": "issue", "status": "confirmed"}, + "acceptance.reference": {"value": "", "source": "prompt", "status": "confirmed"}, + "acceptance.metric_key": {"value": "p95_ttft", "source": "issue", "status": "confirmed", + "authority_reference": ""}, "protocol.comparison": {"value": null, "source": "answer:q:protocol.comparison", "status": "unknown", "asked": true} }, @@ -69,6 +71,7 @@ Each primary task owns an `intake.json` next to its `SKILL.md`. A field declares | `depends_on` | Fields that must be settled before this question applies | | `required_when` | Conditional applicability, e.g. service reuse fields | | `required_before` | Stages this field blocks while it is not settled | +| `user_choice` | Repository-derived values for this decision become suggestions for the user | `task-day-0` fields map to `day0-spec` and stay in the record and the summary. They do not enter a `task-input/v1` file, which rejects unknown keys. @@ -95,8 +98,7 @@ blocks candidate search. ## Question selection -1. A field is asked only when it applies (`depends_on` settled, `required_when` - satisfied), it is still `unknown` and it was never answered `unknown`. +1. Ask applicable missing fields and unconfirmed suggestions. Return the suggested value and its source as an option. Preserve a user’s explicit unknown answer until new confirmed information arrives. 2. A conflicting field is asked before anything else; its options are the recorded candidate values with their sources. 3. Otherwise the lowest missing `batch` is asked as one batch. Answers to other @@ -110,12 +112,36 @@ blocks candidate search. ## Acceptance boundary -A value for an `acceptance.*` field is `confirmed` only when the declared source -is `issue` or `frozen_gate`. A card answer, a prompt statement, a task file or an -interview brief is `proposed`. Proposed values do not unblock candidate search, -do not freeze a gate and do not override a value already confirmed by the -acceptance issue. A record that disagrees with the frozen gate record blocks -candidate search until the user resolves it. +The user identifies the acceptance issue or gate file in the initial prompt, a +confirmed interview brief or a subsequent card answer. A reference suggested by +the workspace or by the gate file itself remains an open question. After intake +has begun, record the user's selection with `answer`. The host is responsible for +passing actual user input to the CLI. The CLI cannot authenticate conversation turns. + +For an issue, first record the user's reference, then include the same +`--set acceptance.reference=` with the issue's values and +`--source issue`. For a frozen task file, pass `--frozen` when recording the +user's selection. For example, after the user chooses the file on a card: + +```text +inferrsi task intake answer --record --question q:acceptance.reference \ + --value --frozen +``` + +The record retains the selected file's explicit acceptance values. Defaults and +arbitrary `--set` values cannot fill missing gate fields. If the file is first +presented later, or its acceptance contents change, evaluating it reopens the +reference question. Conflicting metric values remain visible. Reconfirm the +file and resolve conflicting proposals with the user before search. + +For a vague performance request, the objective and metric must be selected before +baseline measurement. Workspace facts can identify the hardware and model. +Inferred objectives, quality checks, workloads and protocol choices produce +questions. User answers can select a metric for baseline calibration, while +candidate search also requires the acceptance values from the selected authority. +Records created by earlier versions are re-evaluated when opened or handed to +a campaign. A cached complete result or a standalone source label cannot confirm +a user's choices. ## Campaign hand-off @@ -137,8 +163,8 @@ file, and the digest is not part of `plan.json`; use `task intake evaluate ## Cards and text fallback -The runtime returns the same question objects to both presentations. A host may -render a native card; otherwise the Agent shows the same questions and options -as a numbered list. Both write answers through `task intake answer`, so the -normalized record is identical. Only the numbered text presentation has been -exercised so far; no host card adapter ships with this contract. +When `evaluate` returns `needs_user_input: true`, the host presents its questions +and waits for a reply. In Codex Desktop the agent invokes the native question +tool. Hosts without cards show the questions as a numbered list. Both record +the user's replies through `task intake answer`. The CLI itself does not display +a desktop widget. diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index 7ad4dbf46..d8b686e15 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -72,25 +72,33 @@ inspection and explicit evidence-ID lookups can use their own operations. ## Confirm the task-performance inputs -Before any measurement, open the shared intake record with the fields the -request already states: +Immediately after entering the primary, run the following in the target workspace. +Start a fresh record for this request. Include only values the user actually supplied +with `--source prompt`. For a request such as “optimize performance”, omit `--set` +and evaluate before building, profiling, measuring or choosing a workload and gates. ```text -python -X utf8 "" task intake evaluate --task task-performance \ - --record --set = --source prompt +python -X utf8 "" task intake evaluate --task task-performance --record --json ``` -Ask the user only the questions it returns: use a native question card when -the host has one, otherwise show the same questions and options as a numbered -list. Record each answer with `task intake answer --record ---question --value ` (or `--unknown`) until `evaluate` reports -`complete: true`. A recorded card answer is a proposal: a threshold is -confirmed only by the acceptance issue or frozen plan. Pass `--frozen -` to compare the record with the frozen gate; a disagreement blocks -candidate search. While a field stays unknown, do only the stages listed in -`allowed_next`. Hand the complete record to `campaign start --intake -`; without it the campaign warns that the intake gate was not -evaluated. +When the result has `needs_user_input: true`, send the first unresolved decisions to +the user now. In Codex Desktop call the available native question tool +(`request_user_input_async`, or `request_user_input` in Plan mode). Group related +fields into a small batch of concrete choices in the user's language. For example, +ask whether the user wants lower latency on one request or higher throughput at a +fixed load, and how to judge output quality. Offer relevant repository findings as +suggestions and allow a custom or unknown answer. Use numbered text only if the host +has no native question tool. End the turn waiting for the reply. An asynchronous +tool acknowledgement, a preselected option and elapsed time leave the questions open. + +Only after the user's reply, record its values using `task intake answer --record + --question --value ` (or `--unknown`). Re-evaluate before +proceeding. Use `--source repo_inspection` for facts observed in the workspace. +A benchmark, previous run or agent-written gate may suggest conditions. The user +must identify the acceptance issue or frozen plan, directly or in an answer. +Use `--frozen ` for its acceptance values. Preserve unresolved +conditions and never run a campaign without its intake to bypass open questions. +Pass the completed record to `campaign start --intake `. ## Optimize an ordinary user project diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 189c3650d..1e364b11f 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -563,7 +563,8 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: evaluate.add_argument("--source", default="prompt", help="Where --set values came from (prompt, issue, task_file, ...)") evaluate.add_argument("--frozen", type=Path, - help="Frozen gate task file; its acceptance fields are compared") + help="Compare a gate task file; import its stated values when the user " + "selects this file as the acceptance reference") evaluate.add_argument("--json", action="store_true") answer = intake_actions.add_parser( "answer", help="Record one answer to an open question and re-evaluate") diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index 2637fa7b9..a05ff48b7 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -37,14 +37,13 @@ STATUSES = ("confirmed", "proposed", "assumed", "unknown", "conflicting", "stale", "superseded") -SETTLED = ("confirmed", "proposed", "assumed") -BLOCKING = ("unknown", "conflicting", "stale", "superseded") +SETTLED = ("confirmed", "proposed") +BLOCKING = ("unknown", "assumed", "conflicting", "stale", "superseded") ACCEPTANCE = "acceptance." -# Sources whose values may confirm an acceptance threshold. Everything else, -# including card answers, stays a proposal until the acceptance issue or the -# frozen plan states it. +# An issue or file can supply acceptance values only for a user-selected reference. AUTHORITATIVE = ("issue", "frozen_gate") +REFERENCE = "acceptance.reference" _QUESTION = "q:" @@ -116,6 +115,8 @@ def bad(path: str, message: str) -> None: not isinstance(option, dict) or "value" not in option for option in options ): bad(f"{where}.options", "must be an array of {value, hint} objects") + if "user_choice" in field and type(field["user_choice"]) is not bool: + bad(f"{where}.user_choice", "must be a boolean") when = field.get("required_when") if when is not None and ( not isinstance(when, dict) or not isinstance(when.get("field"), str) @@ -187,6 +188,12 @@ def bad(field: str, message: str) -> None: if not isinstance(fields, dict): bad("fields", "must be an object") return problems + snapshot = record.get("selected_gate") + if snapshot is not None and not ( + isinstance(snapshot, dict) and isinstance(snapshot.get("reference"), str) + and isinstance(snapshot.get("values"), dict) + ): + bad("selected_gate", "must contain the selected reference and its acceptance values") known = _field_paths(spec) for path, entry in fields.items(): if path not in known: @@ -197,7 +204,7 @@ def bad(field: str, message: str) -> None: continue if entry.get("status") not in STATUSES: bad(path, f"status must be one of {', '.join(STATUSES)}") - if not isinstance(entry.get("source", "unknown"), str): + if not isinstance(entry.get("source"), str): bad(path, "source must be a string") if type(entry.get("asked", False)) is not bool: bad(path, "asked must be a boolean") @@ -254,12 +261,54 @@ def _coerce(field: dict, value: object) -> object: return value -def _status_for(path: str, source: str) -> str: - if path.startswith(ACCEPTANCE) and source not in AUTHORITATIVE: - return "proposed" +def _user_source(path: str, source: str) -> bool: + return source in ("prompt", "grilling_brief") or source == f"answer:{_QUESTION}{path}" + + +def selected_reference(record: dict) -> str | None: + entry = _entry(record, REFERENCE) + if entry["status"] == "confirmed" and _user_source(REFERENCE, entry.get("source", "")): + return entry["value"] + return None + + +def _status_for(field: dict, source: str, *, bound: bool = False) -> str: + path = field["path"] + from_user = _user_source(path, source) + if path == REFERENCE: + return "confirmed" if from_user else "assumed" + if path.startswith(ACCEPTANCE): + if bound: + return "confirmed" + return "proposed" if from_user else "assumed" + if field.get("user_choice") and not from_user: + return "assumed" return "confirmed" +def _bound_value(record: dict, path: str, entry: dict) -> bool: + reference = selected_reference(record) + if not reference or entry.get("authority_reference") != reference: + return False + snapshot = record.get("selected_gate") + if isinstance(snapshot, dict) and snapshot.get("reference") == reference: + return (entry["source"] == "frozen_gate" + and snapshot["values"].get(path) == entry.get("value")) + return entry["source"] == "issue" + + +def reconcile_record(record: dict, spec: dict) -> dict: + """Recheck provenance, including older records that trusted the source label alone.""" + _check(record, spec) + updated = copy.deepcopy(record) + fields = _field_paths(spec) + for path, entry in updated["fields"].items(): + if entry["status"] in ("confirmed", "proposed", "assumed"): + bound = _bound_value(record, path, entry) + entry["status"] = _status_for(fields[path], entry["source"], bound=bound) + return updated + + def _bump(record: dict, next_revision: int) -> None: record["revision"] = next_revision @@ -270,25 +319,38 @@ def _rank(status: str) -> int: def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: """Merge stated values into a copy of ``record``; raise on invalid fields/values.""" - _check(record, spec) + if source.startswith("answer:"): + raise IntakeError("invalid_source", "Use intake answer to record a user reply") if not isinstance(values, dict): raise IntakeError("invalid_record", "values must be a mapping") - updated = copy.deepcopy(record) + updated = reconcile_record(record, spec) fields = _field_paths(spec) + reference = selected_reference(updated) changed = False revision = updated["revision"] for path, raw in values.items(): if path not in fields: raise IntakeError("invalid_field", f"{path} is not a field of {spec['task']}") value = _coerce(fields[path], raw) - status = _status_for(path, source) + entry = {"value": value, "source": source} + if path.startswith(ACCEPTANCE) and path != REFERENCE and source in AUTHORITATIVE: + entry["authority_reference"] = (values.get(REFERENCE) if source == "issue" + else reference) + bound = _bound_value(updated, path, entry) + if not bound: + entry.pop("authority_reference", None) + status = _status_for(fields[path], source, bound=bound) + entry["status"] = status current = updated["fields"].get(path) + if (current and current["status"] == "unknown" and current.get("asked") + and status == "assumed"): + continue if current is not None and not current.get("candidates") and ( current.get("value") == value ): if _rank(status) <= _rank(current.get("status", "unknown")): continue # same value, no stronger source: leave the record unchanged - updated["fields"][path] = {"value": value, "source": source, "status": status} + updated["fields"][path] = entry changed = True continue if (current is not None and current.get("status") == "conflicting" @@ -296,7 +358,7 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: candidates = [item for item in current["candidates"] if item["value"] != value] candidates.append({"value": value, "source": source}) if len({_canonical(item["value"]) for item in candidates}) == 1: - updated["fields"][path] = {"value": value, "source": source, "status": status} + updated["fields"][path] = entry else: updated["fields"][path] = {"value": None, "source": source, "status": "conflicting", @@ -305,14 +367,10 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: continue if (current is not None and current.get("status") not in (None, "unknown") and current.get("value") is not None and current.get("value") != value): - authoritative_new = source in AUTHORITATIVE - authoritative_old = current.get("source") in AUTHORITATIVE - if authoritative_new and not authoritative_old: - # The issue/task file settles a previously stated or proposed value. - updated["fields"][path] = {"value": value, "source": source, - "status": _status_for(path, source)} + if _rank(status) > _rank(current["status"]): + updated["fields"][path] = entry changed = True - elif authoritative_old and not authoritative_new: + elif _rank(status) < _rank(current["status"]): continue # the accepted value wins over a later proposal else: updated["fields"][path] = {"value": None, "source": source, @@ -324,8 +382,7 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: ]} changed = True continue - entry = {"value": value, "source": source, "status": status} - if current is not None and current.get("asked"): + if current is not None and current.get("asked") and status != "assumed": entry["asked"] = True updated["fields"][path] = entry changed = True @@ -371,6 +428,10 @@ def _question(record: dict, spec: dict, field: dict) -> dict: snapshot[dep] = _entry(record, dep).get("value") options = field.get("options", []) entry = _entry(record, field["path"]) + if entry["status"] == "assumed": + suggestion = {"value": entry["value"], "hint": f"suggested by {entry['source']}"} + options = [suggestion, *(item for item in options if item["value"] != entry["value"])] + snapshot["__suggestion__"] = entry["value"] if entry.get("status") == "conflicting" and isinstance(entry.get("candidates"), list): options = [{"value": item["value"], "hint": f"from {item['source']}"} for item in entry["candidates"]] @@ -414,7 +475,7 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: it. A field answered with ``unknown`` is not asked again: it blocks its stage until a later source states it. """ - _check(record, spec) + record = reconcile_record(record, spec) fields = _field_paths(spec) conflicts = _frozen_conflicts(record, spec, frozen) question_fields = [] @@ -430,7 +491,9 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: if not _applicable(record, field): continue entry = _entry(record, field["path"]) - if entry.get("status") == "unknown" and not entry.get("asked"): + if entry["status"] == "assumed" or ( + entry["status"] == "unknown" and not entry.get("asked") + ): missing.append(field) if missing: lowest = min(field.get("batch", 1) for field in missing) @@ -447,7 +510,8 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: continue status = entry.get("status") if status in BLOCKING or ( - path.startswith(ACCEPTANCE) and status != "confirmed" + stage == "candidate_search" and path.startswith(ACCEPTANCE) + and status != "confirmed" ): blocked_by.append({"field": path, "status": status}) if blocked_by: @@ -478,6 +542,7 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: "phase": record["phase"], "primary_task": record["primary_task"], "questions": questions, + "needs_user_input": bool(questions), "blockers": blockers, "conflicts": conflicts, "allowed_next": allowed_next, @@ -500,7 +565,7 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, the field must still be open. A duplicate, stale or inapplicable delivery is rejected, so a late reply to a superseded question changes nothing. """ - _check(record, spec) + record = reconcile_record(record, spec) open_questions = record.get("open_questions") if not isinstance(open_questions, list): raise IntakeError("invalid_record", @@ -525,19 +590,13 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, if field is None: raise IntakeError("unknown_question", f"{question_id} names a field outside {spec['task']}; re-evaluate") - snapshot = {"__primary_task__": record["primary_task"]["value"]} - dependencies = list(field.get("depends_on", [])) - when = field.get("required_when") - if isinstance(when, dict): - dependencies.append(when["field"]) - for dep in dependencies: - snapshot[dep] = _entry(record, dep).get("value") + snapshot = _question(record, spec, field)["depends_on"] if snapshot != question.get("depends_on"): raise IntakeError("stale_answer", f"{question_id} was asked before its dependencies changed; " "re-evaluate") if not _applicable(record, field) or _entry(record, field["path"]).get("status") not in ( - "unknown", "conflicting", + "unknown", "conflicting", "assumed", ): raise IntakeError("stale_answer", f"{question_id} no longer applies; re-evaluate") @@ -549,10 +608,12 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, } _bump(updated, updated["revision"] + 1) else: - updated = set_fields(updated, spec, {field["path"]: value}, - source=f"answer:{question_id}") - entry = updated["fields"][field["path"]] - entry["asked"] = True + source = f"answer:{question_id}" + updated["fields"][field["path"]] = { + "value": _coerce(field, value), "source": source, + "status": _status_for(field, source), "asked": True, + } + _bump(updated, updated["revision"] + 1) updated["open_questions"] = [ item for item in updated["open_questions"] if item.get("id") != question_id] return updated @@ -564,11 +625,11 @@ def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: confirmed, proposed, unknown = {}, {}, [] for field in spec["fields"]: path = field["path"] - entry = _entry(record, path) - status = entry.get("status") + entry = view["fields"].get(path, {}) + status = entry.get("status", "unknown") if status == "confirmed": confirmed[path] = entry.get("value") - elif status == "proposed": + elif status in ("proposed", "assumed"): proposed[path] = entry.get("value") elif status in ("unknown", "conflicting", "stale", "superseded"): unknown.append(path) diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index f41efd6b4..6a4d986c4 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -86,7 +86,7 @@ def frozen_values(path: Path) -> dict: # ``reference`` names the gate record itself and is path-normalized by the task # contract, so it is not compared; ``task_input.frozen_gate`` makes the same choice. return {f"acceptance.{name}": value for name, value in acceptance.items() - if value is not None and name != "reference"} + if name != "reference" and preview["sources"][f"acceptance.{name}"] == "yaml"} def parse_sets(items: list[str]) -> dict: @@ -100,6 +100,8 @@ def parse_sets(items: list[str]) -> dict: def _persist(path: Path, record: dict, view: dict) -> None: + for path_key, field in record["fields"].items(): + field["status"] = view["fields"][path_key]["status"] record["open_questions"] = view["questions"] record["blockers"] = view["blockers"] record["conflicts"] = view["conflicts"] @@ -108,9 +110,41 @@ def _persist(path: Path, record: dict, view: dict) -> None: write_record(path, record) +def _evaluate_and_save(path: Path, record: dict, spec: dict, frozen_path: Path | None, + *, selecting_reference: bool) -> dict: + frozen = frozen_values(frozen_path) if frozen_path else None + reference = intake.selected_reference(record) + if frozen and reference and Path(reference).resolve() == frozen_path.resolve(): + snapshot = {"reference": reference, "values": frozen} + if selecting_reference: + record["selected_gate"] = snapshot + if record.get("selected_gate") == snapshot: + # Preserve disagreements for the frozen-gate comparison. + matching = {} + for field in spec["fields"]: + key = field["path"] + entry = record["fields"].get(key, {}) + if key in frozen and entry.get("status") != "conflicting": + if entry.get("value") in (None, frozen[key]): + matching[key] = frozen[key] + record = intake.set_fields(record, spec, matching, source="frozen_gate") + else: + # The file is new or changed since the selection. Re-open the reference + # question and persist the revocation before handing off to campaign start. + record.pop("selected_gate", None) + record["fields"][intake.REFERENCE] = { + "value": reference, "source": "repo_inspection", "status": "assumed", + } + record["revision"] += 1 + view = intake.evaluate(record, spec, frozen=frozen) + _persist(path, record, view) + return view + + def evaluate_command(args) -> dict: record_path = Path(args.record) - if record_path.is_file(): + existing = record_path.is_file() + if existing: record = read_record(record_path) else: if not args.task: @@ -121,13 +155,16 @@ def evaluate_command(args) -> dict: raise intake.IntakeError( "task_mismatch", f"the record already records {record['task']}, not {args.task}") spec = load_spec(record["task"]) + record = intake.reconcile_record(record, spec) values = parse_sets(args.set) + selecting = intake.REFERENCE in values and args.source in ("prompt", "grilling_brief") + if existing and selecting and intake.selected_reference(record) != values[intake.REFERENCE]: + raise intake.IntakeError("user_answer_required", + "Use the acceptance reference question to record the user's reply") if values: record = intake.set_fields(record, spec, values, source=args.source) - frozen = frozen_values(args.frozen) if args.frozen else None - view = intake.evaluate(record, spec, frozen=frozen) - _persist(record_path, record, view) - return view + return _evaluate_and_save(record_path, record, spec, args.frozen, + selecting_reference=selecting and not existing) def answer_command(args) -> dict: @@ -136,10 +173,8 @@ def answer_command(args) -> dict: spec = load_spec(record["task"]) record = intake.answer(record, spec, question_id=args.question, value=args.value, unknown=bool(args.unknown)) - frozen = frozen_values(args.frozen) if args.frozen else None - view = intake.evaluate(record, spec, frozen=frozen) - _persist(record_path, record, view) - return view + return _evaluate_and_save(record_path, record, spec, args.frozen, + selecting_reference=args.question == f"q:{intake.REFERENCE}") def summary_command(args) -> dict: @@ -191,6 +226,9 @@ def attach_record(session_dir: Path, record: dict, gate: dict) -> dict: def _render_questions(view: dict) -> list[str]: lines = [] if view["questions"]: + lines.append("Ask the user the following questions using the host question-card tool. " + "Wait for their reply before measurement or candidate work. " + "Use numbered text when the tool is unavailable.") lines.append("questions:") for question in view["questions"]: lines.append(f" {question['id']} {question['question']}") diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md index 4e64038cf..19a8b677d 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md @@ -34,6 +34,17 @@ metadata: ## Capture the actual run +First evaluate a fresh `task-performance` intake record using only information the +user stated. A generic optimization request leaves the objective, metric and +quality check open, even in a repository with existing benchmarks. Before building +or measuring, run `task intake evaluate --task task-performance --record +--json`. When questions are returned, call the host's native question-card tool now +(on Codex Desktop, `request_user_input_async` when available). Ask the user which +outcome and quality check to use. Present repository-derived options as suggestions. +Use numbered questions if the host lacks cards. Wait for an actual reply, including +after an asynchronous card is accepted for display. A new local gate file or a +source label cannot stand in for the user's selection of an acceptance reference. + Record the hardware vendor, device SKU, backend and driver, OS, model family and checkpoint revision, engine and plugin versions, and the exact run script and flags. Attach the benchmark inputs, workload shape, dtype, reference or quality diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json index 49166c712..72dddcd5c 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json @@ -5,11 +5,12 @@ "fields": [ { "path": "optimization.objective", + "user_choice": true, "maps_to": "task-input/v1", "batch": 1, "type": "text", "question": "Which outcome decides this round?", - "required_before": ["candidate_search"] + "required_before": ["baseline_measurement", "candidate_search"] }, { "path": "acceptance.metric_key", @@ -23,7 +24,7 @@ {"value": "p95_tpot", "hint": "p95 time per output token"}, {"value": "peak_memory", "hint": "peak device memory under the fixed load"} ], - "required_before": ["candidate_search"] + "required_before": ["baseline_measurement", "candidate_search"] }, { "path": "acceptance.metric_unit", @@ -72,6 +73,7 @@ }, { "path": "environment.quality_command", + "user_choice": true, "maps_to": "task-input/v1", "batch": 1, "type": "text", @@ -80,6 +82,7 @@ }, { "path": "protocol.quality_failure_policy", + "user_choice": true, "maps_to": "summary-only", "batch": 1, "type": "choice", @@ -92,6 +95,7 @@ }, { "path": "protocol.timing_boundary", + "user_choice": true, "maps_to": "summary-only", "batch": 1, "type": "text", @@ -148,6 +152,7 @@ }, { "path": "optimization.workload", + "user_choice": true, "maps_to": "task-input/v1", "batch": 2, "type": "text", @@ -164,6 +169,7 @@ }, { "path": "environment.repetitions", + "user_choice": true, "maps_to": "task-input/v1", "batch": 2, "type": "integer", @@ -172,6 +178,7 @@ }, { "path": "environment.max_minutes", + "user_choice": true, "maps_to": "task-input/v1", "batch": 2, "type": "number", @@ -180,6 +187,7 @@ }, { "path": "protocol.comparison", + "user_choice": true, "maps_to": "campaign-protocol", "batch": 3, "type": "choice", @@ -192,6 +200,7 @@ }, { "path": "protocol.service_lifecycle", + "user_choice": true, "maps_to": "summary-only", "batch": 3, "type": "text", @@ -210,6 +219,7 @@ }, { "path": "optimization.plane", + "user_choice": true, "maps_to": "task-input/v1", "batch": 3, "type": "choice", @@ -223,6 +233,7 @@ }, { "path": "environment.rounds", + "user_choice": true, "maps_to": "task-input/v1", "batch": 3, "type": "integer", diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index d03ad75b7..22e478ab4 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -32,12 +32,13 @@ def build(paths: set[str] | None = None, *, task: str = "task-performance") -> d chosen = {path: value for path, value in ALL_VALUES.items() if paths is None or path in paths} stated = {path: value for path, value in chosen.items() - if not path.startswith("acceptance.")} + if path in COMPLETE["fields"]["values"]} accepted = {path: value for path, value in chosen.items() - if path.startswith("acceptance.")} + if path in COMPLETE["acceptance"]["values"]} if stated: record = intake.set_fields(record, spec, stated, source="prompt") if accepted: + accepted[intake.REFERENCE] = ALL_VALUES[intake.REFERENCE] record = intake.set_fields(record, spec, accepted, source="issue") return record @@ -117,11 +118,12 @@ def test_unknown_answer_blocks_its_stage_and_is_not_asked_again(): def test_stale_answer_after_a_dependency_change_is_rejected(): spec = spec_for() - record = build({"acceptance.metric_key"}) + record = build({"acceptance.metric_key", intake.REFERENCE}) record, view = ask(record, spec) question = next(item for item in view["questions"] if item["field"] == "acceptance.min_improvement_pct") - changed = intake.set_fields(record, spec, {"acceptance.metric_key": "p99_ttft"}, + changed = intake.set_fields(record, spec, {"acceptance.metric_key": "p99_ttft", + intake.REFERENCE: ALL_VALUES[intake.REFERENCE]}, source="issue") with pytest.raises(intake.IntakeError) as error: intake.answer(changed, spec, question_id=question["id"], value=5) @@ -160,8 +162,9 @@ def test_acceptance_issue_confirms_a_previously_proposed_value(): record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, source="prompt") assert record["fields"]["acceptance.metric_key"]["status"] == "proposed" - record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, - source="issue") + record = intake.set_fields(record, spec, {intake.REFERENCE: "accepted issue"}, source="prompt") + record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft", + intake.REFERENCE: "accepted issue"}, source="issue") assert record["fields"]["acceptance.metric_key"]["status"] == "confirmed" @@ -282,7 +285,8 @@ def test_only_the_issue_or_frozen_record_confirms_an_acceptance_value(source): spec = spec_for() record = intake.new_record("task-performance", record_id="intake-source") record = intake.set_fields(record, spec, {"acceptance.metric_key": "p95_ttft"}, source=source) - assert record["fields"]["acceptance.metric_key"]["status"] == "proposed" + expected = "proposed" if source in ("prompt", "grilling_brief") else "assumed" + assert record["fields"]["acceptance.metric_key"]["status"] == expected def test_campaign_gate_blocks_until_complete(tmp_path): @@ -370,3 +374,105 @@ def test_frozen_conflict_via_cli(tmp_path, capsys): assert result["complete"] is False assert result["conflicts"][0]["field"] == "acceptance.metric_key" assert result["conflicts"][0]["frozen_value"] == "p99_ttft" + + +def test_self_written_gate_keeps_campaign_blocked(project, tmp_path, capsys): # noqa: F811 + record_path = tmp_path / "record.json" + gate_file = tmp_path / "gate.json" + proposed = {**COMPLETE["acceptance"]["values"], intake.REFERENCE: str(gate_file)} + gate_file.write_text(json.dumps({"schema_version": 1, "acceptance": { + key.removeprefix("acceptance."): value for key, value in proposed.items() + }})) + cmd = ["task", "intake", "evaluate", "--record", str(record_path), "--json"] + guesses = dict(COMPLETE["fields"]["values"]) + guesses.pop(intake.REFERENCE) + for source, values, options in ( + ("workspace", guesses, ["--task", "task-performance"]), + ("frozen_gate", proposed, ["--frozen", str(gate_file)]), + ): + args = [] + for key, value in values.items(): + args.extend(("--set", f"{key}={value}")) + assert cli.main([*cmd, *options, "--source", source, *args]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["needs_user_input"] and not result["complete"] + assert result["allowed_next"] == ["read_only_preparation"] + questions = {q["field"]: q for q in result["questions"]} + assert {"optimization.objective", "acceptance.metric_key", intake.REFERENCE} <= questions.keys() + metric_option = questions["acceptance.metric_key"]["options"][0] + assert metric_option["value"] == proposed["acceptance.metric_key"] + assert result["fields"]["environment.backend"]["status"] == "confirmed" + assert result["fields"]["optimization.objective"]["status"] == "assumed" + assert result["fields"]["acceptance.metric_key"]["status"] == "assumed" + assert cli.main([*cmd, "--set", f"{intake.REFERENCE}={gate_file}"]) == 2 + assert json.loads(capsys.readouterr().out)["error"] == "user_answer_required" + assert cli.main(start_arguments(project, extra=("--intake", str(record_path)))) == 2 + capsys.readouterr() + assert not project[3].exists() + + # Records written before this fix may already say every workspace/gate value + # was confirmed and cache a complete result. The execution path must recheck. + record = json.loads(record_path.read_text()) + for field in record["fields"].values(): + field["status"] = "confirmed" + record.update(complete=True, open_questions=[], allowed_next=["candidate_search"]) + record_path.write_text(json.dumps(record)) + assert task_intake.campaign_gate(record_path)[0]["status"] == "blocked" + + +def test_selected_gate_imports_only_its_values_and_changed_file_reopens_card(tmp_path, capsys): + record = tmp_path / "record.json" + gate = tmp_path / "gate.yaml" + gate.write_bytes((PERFORMANCE / "frozen-gate.yaml").read_bytes()) + cmd = ["task", "intake", "evaluate", "--record", str(record), "--json"] + assert cli.main([*cmd, "--task", "task-performance"]) == 0 + capsys.readouterr() + + # This is the separate reply to the outstanding reference question. + answer = ["task", "intake", "answer", "--record", str(record), "--question", + "q:acceptance.reference", "--value", str(gate), "--frozen", str(gate), "--json"] + assert cli.main(answer) == 0 + view = json.loads(capsys.readouterr().out) + assert view["fields"]["acceptance.metric_key"]["status"] == "confirmed" + assert view["fields"][intake.REFERENCE]["source"] == "answer:q:acceptance.reference" + assert cli.main([*cmd, "--source", "frozen_gate", "--set", + "acceptance.min_improvement_pct=99"]) == 0 + assert json.loads(capsys.readouterr().out)["fields"]["acceptance.min_improvement_pct"][ + "value"] == 10 + + gate.write_bytes((PERFORMANCE / "frozen-mismatch.yaml").read_bytes()) + assert cli.main([*cmd, "--frozen", str(gate)]) == 0 + view = json.loads(capsys.readouterr().out) + assert any(q["field"] == intake.REFERENCE for q in view["questions"]) + assert view["fields"]["acceptance.metric_key"]["status"] == "assumed" + assert task_intake.campaign_gate(record)[0]["status"] == "blocked" + + +def test_fully_specified_request_selects_existing_gate_without_questions(tmp_path, capsys): + gate = PERFORMANCE / "frozen-gate.yaml" + record = tmp_path / "record.json" + values = {**COMPLETE["fields"]["values"], intake.REFERENCE: str(gate)} + args = ["task", "intake", "evaluate", "--task", "task-performance", "--record", + str(record), "--frozen", str(gate), "--json"] + for key, value in values.items(): + args.extend(("--set", f"{key}={value}")) + assert cli.main(args) == 0 + result = json.loads(capsys.readouterr().out) + assert result["complete"] and not result["needs_user_input"] + assert task_intake.campaign_gate(record)[0]["status"] == "ready" + + +def test_user_can_replace_suggested_goal_and_settle_a_conflict(): + spec = spec_for() + record = intake.new_record("task-performance", record_id="intake-suggested") + record = intake.set_fields(record, spec, {"optimization.objective": "throughput"}, + source="repo_inspection") + record, _ = ask(record, spec) + record = intake.answer(record, spec, question_id="q:optimization.objective", value="latency") + assert record["fields"]["optimization.objective"]["value"] == "latency" + assert record["fields"]["optimization.objective"]["status"] == "confirmed" + record = intake.set_fields(record, spec, {"optimization.objective": "memory"}, source="prompt") + record, view = ask(record, spec) + assert view["questions"][0]["field"] == "optimization.objective" + record = intake.answer(record, spec, question_id="q:optimization.objective", value="latency") + assert record["fields"]["optimization.objective"]["status"] == "confirmed" diff --git a/tests/fixtures/intake/performance/complete.json b/tests/fixtures/intake/performance/complete.json index f699717bf..99e908191 100644 --- a/tests/fixtures/intake/performance/complete.json +++ b/tests/fixtures/intake/performance/complete.json @@ -6,6 +6,7 @@ "values": { "optimization.objective": "reduce p95 TTFT for the fixed decode workload", "optimization.repository": ".", + "acceptance.reference": "plan/acceptance.md", "optimization.model": "", "optimization.model_revision": "", "optimization.framework": "vllm", @@ -31,7 +32,6 @@ "acceptance.metric_unit": "ms", "acceptance.direction": "minimize", "acceptance.min_improvement_pct": 10, - "acceptance.reference": "plan/acceptance.md", "acceptance.baseline_revision": "" } } From 3f78f6326cde8c4b3a58648640d3ba29061bcb37 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 11:47:35 +0800 Subject: [PATCH 05/26] Refresh generated indexes for performance intake confirmation Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/searchspace-index.json | 2 +- docs/skill-coverage.md | 2 +- .../knowledge/data/skill_library/_compiled/_provenance.json | 2 +- .../knowledge/data/skill_library/_compiled/inputs.json | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index 63aa49540..b1bce6512 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -6,7 +6,7 @@ "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "047e0ff9e089594c2dce41952fccb630218b80b192033545a5fad6871e419646" + "metadata_sha256": "0b0032869e4e437357898c2ab956d1ec8497aa4b2f9a76880684db9fd66dae05" }, "skills": { "ascend-aclgraph-capture-replay": {"path": "systems/platforms/ascend/ascend-aclgraph-capture-replay/SKILL.md", "state": "covered", "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], ["Accelerator", "Optimize"], ["Accelerator", "Verify"]]}, diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index e8851159e..53ed28bcb 100644 --- a/docs/skill-coverage.md +++ b/docs/skill-coverage.md @@ -4,7 +4,7 @@ Generated from the registry, SKILL.md frontmatter and the two maintained matrices. **Do not edit by hand**; regenerate after any registry, skill, matrix or frozen-plan change. -- Input digest: `sha256:dd49b8b1cd3b96e43a7f60e5b7ca2273be1d96d8dc835196fe6f249611e62551` +- Input digest: `sha256:d44b87d8f3a7619032c0b145e6657e3245b01bd3b12348295ec9795c95943770` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 3b53ca7a5..8337d9630 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "c69930dfdba3cdaba28b0f7f18abd7a1b9a702e3", + "source_revision": "9bbbf4edf45a0d793c969f9bc9d85d901f7c22e5", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index 8be71ce19..755894cb2 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -1205,8 +1205,8 @@ "description": "Use when a correct inference baseline misses a latency, throughput, memory or cost target. Compare compatible changes under the user's workload and quality gate." }, "files": { - "SKILL.md": "29051a9dfbca6591374e715d8021f5af9748532baf1da1c7c49f4a0319653eda", - "intake.json": "6bc9a33c6c6da11d91686a135b7dd59017333851af3f563732ba5d901198e8d3" + "SKILL.md": "2fc9b33415ae51cbb9ef8c1135afa8512f19693fd0d157069d9312dbe5eabea2", + "intake.json": "e91cebd1f3dbe5aec9f41ceebbefdfc56a73e17b3c139af925537d06817ceda7" } }, "task-version-alignment": { From e4cab3fc2abdbeb5f7faead828efe8a398b72fa1 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 13:07:34 +0800 Subject: [PATCH 06/26] Require a separate approval of the quantified performance brief Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- AGENTS.md | 4 + docs/guides/operations.md | 6 +- docs/guides/task-intake.md | 48 ++++-- plugins/inferrsi/skills/inferrsi/SKILL.md | 20 ++- src/inferrsi/apps/cli/intake_contract.py | 76 +++++++++- src/inferrsi/apps/cli/task_intake.py | 61 ++++++-- .../tasks/task-performance/SKILL.md | 19 +++ .../tasks/task-performance/intake.json | 65 +++++++++ tests/apps/test_task_intake.py | 138 ++++++++++++++++-- .../fixtures/intake/performance/complete.json | 11 +- 10 files changed, 402 insertions(+), 46 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f184c2637..68c4d4436 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,6 +99,10 @@ Portable operator guidance and candidate procedures live in the [skill library]( Benchmark comparisons, ordinary project optimization and packaged optimization tasks each have one entry workflow; see [optimization requests](docs/guides/operations.md#optimization-requests). +For interactive project performance work, collect the numeric performance goal, +benchmark and quantitative quality gate through [task intake](docs/guides/task-intake.md). +Read back the complete task brief and obtain a separate approval on a native +question card before measurement or candidate edits. ## Dev smoke (local) diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 36e133281..d88200aed 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -33,7 +33,7 @@ Effect classes used below: | Inspect a store candidate's history | Python `open_knowledge_store(...).history` | Read-only | Opens an existing store and reads the revision lineage for one store ID | | Amend repository-owned knowledge | Scoped repository PR | — | Repository review and integration authority apply; this is not a runtime store Update | | Validate or preview a YAML task file | CLI `task validate` / `task preview [--json]` / `task schema` / `task template`; [task input](task-input.md) | Read-only | Reads one schema v1 task file and prints field errors, effective normalized values, their sources and plan/run blockers. Starts no process or probe and writes no workspace, plan, run or evidence file. A complete preview does not authorize execution | -| Confirm missing inputs before a measured task | CLI `task intake evaluate` / `answer` / `summary [--json]`; `campaign start --intake`; [task intake](task-intake.md) | Local record | Evaluates an intake/v1 record against the packaged field spec and returns the questions that unblock the next stage. `evaluate` and `answer` write only the caller-named record file; `summary` reads. Starts no process or probe. A complete record does not authorize execution or freeze a gate | +| Confirm missing inputs before a measured task | CLI `task intake evaluate` / `answer` / `summary [--json]`; `campaign start --intake`; [task intake](task-intake.md) | Local record | Evaluates an intake/v1 record against the packaged field spec and returns the questions that unblock the next stage. `evaluate` and `answer` update the named record under a sibling file lock; `summary` reads. Starts no process or probe. A complete record does not authorize execution or freeze a gate | | Inspect/prepare experiments | CLI `doctor`; `plan` or `--dry-run` | Read-only inspection / preview | `doctor` may invoke bounded probes and does not certify target compatibility; `plan` previews a specification without persisting a campaign or authorizing execution | | Execute/inspect experiments | CLI `run`; `status`; `report` | Experiment-executing / read-only / report-generating | `run` executes caller-supplied commands and records evidence; `status` reads recorded progress; `report` generates HTML from recorded evidence | | Deliver retained results | CLI `export --input --output [--agent-job]`; Python `apps.delivery.export_bundle` / `read_bundle` | Report-generating | Publishes Markdown, offline HTML, versioned result JSON and artifact index from one snapshot without remeasurement. Optional native-job input verifies standalone Benchmark terminal token usage. Iterative CLI final returns separate delivery status. See [result delivery](result-delivery.md) and [Benchmark metrics](../benchmarks/benchmark-metrics.md) | @@ -531,7 +531,9 @@ snapshot pinned at startup. The campaign Dashboard remains available through and follow `next_action`. The default comparison uses Qwen denoising and MoE forward in independent on/off sessions. See the [comparison workflow](../benchmarks/benchmark-comparison.md). - **Optimize your project.** Use `inferrsi campaign` in the current Agent - conversation. Supply the workload, metric, gates, scripts and budget, then + conversation. Collect the quantitative performance target, benchmark, accuracy + bound, scripts and budget through [task intake](task-intake.md). Read back + the complete brief and obtain a separate user approval before measurement, then record the measured bottleneck before candidate search. The [shared workflow](optimization-workflow-unification.md) defines round limits, recovery and dashboard generation from the Harness control record. diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 4f78c5f38..2f571de04 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -10,7 +10,8 @@ reach a task file. The contract is `inferrsi.apps.cli.intake_contract`; the commands are `inferrsi task intake ...`. Nothing here starts a process, probes a device or -freezes a gate. `evaluate` and `answer` write only the `--record` file the caller names. +freezes a gate. `evaluate` and `answer` update the named record under a sibling `.lock` file. +If an update is in progress, retry after it finishes. ## Files @@ -42,7 +43,7 @@ freezes a gate. `evaluate` and `answer` write only the `--record` file the calle "open_questions": [], "blockers": [], "conflicts": [], - "allowed_next": ["read_only_preparation", "baseline_measurement"], + "allowed_next": ["read_only_preparation"], "execution": "not started" } ``` @@ -134,14 +135,33 @@ presented later, or its acceptance contents change, evaluating it reopens the reference question. Conflicting metric values remain visible. Reconfirm the file and resolve conflicting proposals with the user before search. -For a vague performance request, the objective and metric must be selected before -baseline measurement. Workspace facts can identify the hardware and model. -Inferred objectives, quality checks, workloads and protocol choices produce -questions. User answers can select a metric for baseline calibration, while -candidate search also requires the acceptance values from the selected authority. -Records created by earlier versions are re-evaluated when opened or handed to -a campaign. A cached complete result or a standalone source label cannot confirm -a user's choices. +## Final performance brief + +A final goal has a metric, direction and numeric target. For an absolute +target supply the bound in the metric unit. For a relative target supply the +minimum percent improvement over the pinned baseline. The per-candidate +retention rule remains a separate input. State the workload, accuracy benchmark +and split, quality metric, comparison, numeric threshold and unit. Include the +command that evaluates that condition. Repository findings are suggestions +until the user chooses them. + +Once all applicable fields and acceptance sources are settled, `evaluate` or +the last field `answer` returns a `task_brief`, `brief_review: +awaiting_confirmation` and one revision-specific question. Read the **whole** +brief back in the user's language and send a separate native approve-or-revise +card. Hosts without cards use the same explicit decision in text. Record the +reply against the exact question displayed: + +```text +inferrsi task intake answer --record --question --value approve +``` + +An explicit `revise` or unknown reply keeps work paused until edits and a new +review. A missing reply leaves the card open. Capture corrections through intake, +resolve any conflicts and present the revised brief before asking again. +The question ID binds the record, field revision and applicable values. +Evaluation and summary alone cannot grant approval. Measured work requires +`brief_review: approved`. Older records are re-evaluated on use. ## Campaign hand-off @@ -156,10 +176,10 @@ and its sha256 is returned in the start result. Without `--intake`, start prints a warning to stderr that the gate was not evaluated and proceeds as before. -The gate checks that the record is complete. It does not yet compare the record -with the campaign's own metric, quality and budget flags or with a frozen gate -file, and the digest is not part of `plan.json`; use `task intake evaluate ---frozen` for the gate comparison. +The gate rechecks a selected local gate snapshot and the current brief decision. +The caller must supply campaign flags and validators matching the approved brief, +including its final target and accuracy bound. The retained intake digest is +returned with the start result. ## Cards and text fallback diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index d8b686e15..17197b16d 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -98,7 +98,25 @@ A benchmark, previous run or agent-written gate may suggest conditions. The user must identify the acceptance issue or frozen plan, directly or in an answer. Use `--frozen ` for its acceptance values. Preserve unresolved conditions and never run a campaign without its intake to bypass open questions. -Pass the completed record to `campaign start --intake `. +Collect a numeric final performance goal (metric, direction, absolute bound and +unit or minimum percent improvement over the baseline). Ask which benchmark, +version/split, workload and concurrency to replay. Confirm the quality metric, +comparison, numeric tolerance and unit. A script name, "faster", "no quality +loss", and a per-candidate retention default leave decisions open. A selected +plan can supply explicit criteria; show them to the user in the brief. + +When `brief_review` becomes `awaiting_confirmation`, read back the **complete +task brief** in the user's language. Include the performance and accuracy +inequalities, both benchmark inputs, baseline, model/device, timing and +comparison, commands, change scope, failure policy and budget from +`task_brief.conditions`. Then send a **separate native card** asking the user +to approve this exact brief or request changes. Wait for a fresh explicit reply. +Record it with `task intake answer` using the returned `q:task_brief:...` ID and +`approve` or `revise`. For revisions, apply the corrections and present the +entire updated brief on a fresh card. This final review also applies to a fully +specified initial prompt. Until approval, allow only read-only preparation. +Pass the approved record to `campaign start --intake ` and use its +criteria in the frozen protocol and final evaluation. ## Optimize an ordinary user project diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index a05ff48b7..a03fa9b89 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -15,6 +15,7 @@ from __future__ import annotations import copy +import hashlib import json import math @@ -46,6 +47,7 @@ REFERENCE = "acceptance.reference" _QUESTION = "q:" +_BRIEF_QUESTION = "q:task_brief:" class IntakeError(ValueError): @@ -206,6 +208,11 @@ def bad(field: str, message: str) -> None: bad(path, f"status must be one of {', '.join(STATUSES)}") if not isinstance(entry.get("source"), str): bad(path, "source must be a string") + if entry.get("status") in SETTLED: + try: + _coerce(known[path], entry.get("value")) + except IntakeError as exc: + bad(path, str(exc)) if type(entry.get("asked", False)) is not bool: bad(path, "asked must be a boolean") return problems @@ -310,6 +317,7 @@ def reconcile_record(record: dict, spec: dict) -> dict: def _bump(record: dict, next_revision: int) -> None: + record.pop("brief_decision", None) record["revision"] = next_revision @@ -467,6 +475,35 @@ def _frozen_conflicts(record: dict, spec: dict, frozen: dict | None) -> list[dic return conflicts +def _performance_brief(record: dict, spec: dict) -> dict: + values = {field["path"]: _coerce(field, record["fields"][field["path"]]["value"]) + for field in spec["fields"] if _applicable(record, field)} + metric = values["acceptance.metric_key"] + target = values["protocol.target_value"] + if values["protocol.target_kind"] == "relative_improvement_pct": + performance = f"{metric}: improve by at least {target:g}% over the pinned baseline" + else: + comparison = "<=" if values["acceptance.direction"] == "minimize" else ">=" + performance = f"{metric} {comparison} {target:g} {values['acceptance.metric_unit']}" + operators = {"at_least": ">=", "at_most": "<=", "equal": "="} + operator = operators[values["protocol.quality_comparator"]] + quality = (f"{values['protocol.quality_metric']} {operator} " + f"{values['protocol.quality_limit']:g} {values['protocol.quality_unit']}") + brief = {"record_id": record["record_id"], "revision": record["revision"], + "task": record["task"], "performance_target": performance, "quality_gate": quality, + "benchmark": values["protocol.quality_benchmark"], "conditions": values} + brief["id"] = _BRIEF_QUESTION + hashlib.sha256(_canonical(brief).encode()).hexdigest() + return brief + + +def _brief_question(brief: dict) -> dict: + return {"id": brief["id"], "field": "task_brief", + "question": "After reviewing the complete task brief, do you approve this revision?", + "options": [{"value": "approve", "hint": "accept the brief as shown"}, + {"value": "revise", "hint": "request changes and keep execution blocked"}], + "fallback": "unknown"} + + def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: """Return the questions, blockers, conflicts and allowed next steps. @@ -526,6 +563,27 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: blockers.append({"stage": "candidate_search", "blocked_by": entries}) else: existing["blocked_by"].extend(entries) + brief = None + review = "not_required" + if spec["task"] == "task-performance": + review = "collecting_inputs" + if not blockers and not conflicts: + brief = _performance_brief(record, spec) + decision = record.get("brief_decision") + review = "awaiting_confirmation" + if decision == {"question": brief["id"], "value": "approve"}: + review = "approved" + elif decision == {"question": brief["id"], "value": "revise"}: + review = "changes_requested" + else: + questions = [_brief_question(brief)] + if review != "approved": + for stage in ("baseline_measurement", "candidate_search"): + blocker = next((item for item in blockers if item["stage"] == stage), None) + if blocker is None: + blocker = {"stage": stage, "blocked_by": []} + blockers.append(blocker) + blocker["blocked_by"].append({"field": "task_brief", "status": review}) blocked_stages = {item["stage"] for item in blockers} # Device and service execution always need a separate authorization; the # record only unlocks preparation, baseline measurement and candidate search. @@ -542,7 +600,9 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: "phase": record["phase"], "primary_task": record["primary_task"], "questions": questions, - "needs_user_input": bool(questions), + "needs_user_input": bool(questions) or review == "changes_requested", + "brief_review": review, + "task_brief": brief, "blockers": blockers, "conflicts": conflicts, "allowed_next": allowed_next, @@ -585,6 +645,18 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, f"{question_id} is not open in the current record; re-evaluate") raise IntakeError("unknown_question", f"No recorded open question {question_id}; run evaluate first") + if question_id.startswith(_BRIEF_QUESTION): + view = evaluate(record, spec) + if (view["brief_review"] != "awaiting_confirmation" + or view["task_brief"]["id"] != question_id): + raise IntakeError("stale_answer", "Present the current task brief before answering") + if unknown: + value = "revise" + if value not in ("approve", "revise"): + raise IntakeError("invalid_value", "Reply to the task brief with approve or revise") + record["brief_decision"] = {"question": question_id, "value": value} + record["open_questions"] = [] + return record fields = _field_paths(spec) field = fields.get(question.get("field")) if field is None: @@ -640,6 +712,8 @@ def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: "revision": record["revision"], "primary_task": record["primary_task"], "phase": record["phase"], + "task_brief": view["task_brief"], + "brief_review": view["brief_review"], "confirmed": confirmed, "proposed": proposed, "unknown": unknown, diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 6a4d986c4..103bd89ce 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -16,6 +16,7 @@ from importlib.resources import files from pathlib import Path +from ..storage.artifacts import file_lock from . import intake_contract as intake @@ -110,14 +111,22 @@ def _persist(path: Path, record: dict, view: dict) -> None: write_record(path, record) -def _evaluate_and_save(path: Path, record: dict, spec: dict, frozen_path: Path | None, - *, selecting_reference: bool) -> dict: +def _evaluate_gate(record: dict, spec: dict, frozen_path: Path | None, + *, selecting_reference: bool) -> tuple[dict, dict | None]: + snapshot = record.get("selected_gate") + selected_path = None + if snapshot: + selected_path = Path(record.get("selected_gate_file", snapshot["reference"])) + if frozen_path is None: + frozen_path = selected_path frozen = frozen_values(frozen_path) if frozen_path else None reference = intake.selected_reference(record) - if frozen and reference and Path(reference).resolve() == frozen_path.resolve(): + reference_path = selected_path or (Path(reference) if reference else None) + if frozen_path and reference and reference_path.resolve() == frozen_path.resolve(): snapshot = {"reference": reference, "values": frozen} if selecting_reference: record["selected_gate"] = snapshot + record["selected_gate_file"] = str(frozen_path.resolve()) if record.get("selected_gate") == snapshot: # Preserve disagreements for the frozen-gate comparison. matching = {} @@ -132,10 +141,19 @@ def _evaluate_and_save(path: Path, record: dict, spec: dict, frozen_path: Path | # The file is new or changed since the selection. Re-open the reference # question and persist the revocation before handing off to campaign start. record.pop("selected_gate", None) + record.pop("selected_gate_file", None) + record.pop("brief_decision", None) record["fields"][intake.REFERENCE] = { "value": reference, "source": "repo_inspection", "status": "assumed", } record["revision"] += 1 + return record, frozen + + +def _evaluate_and_save(path: Path, record: dict, spec: dict, frozen_path: Path | None, + *, selecting_reference: bool) -> dict: + record, frozen = _evaluate_gate(record, spec, frozen_path, + selecting_reference=selecting_reference) view = intake.evaluate(record, spec, frozen=frozen) _persist(path, record, view) return view @@ -180,7 +198,7 @@ def answer_command(args) -> dict: def summary_command(args) -> dict: record = read_record(Path(args.record)) spec = load_spec(record["task"]) - frozen = frozen_values(args.frozen) if args.frozen else None + record, frozen = _evaluate_gate(record, spec, args.frozen, selecting_reference=False) return intake.summary(record, spec, frozen=frozen) @@ -196,7 +214,8 @@ def campaign_gate(path: Path, *, expected_task: str = "task-performance", raise intake.IntakeError( "task_mismatch", f"{path} records {record.get('task')}, not {expected_task}") spec = load_spec(expected_task) - view = intake.evaluate(record, spec, frozen=frozen) + record, selected = _evaluate_gate(record, spec, None, selecting_reference=False) + view = intake.evaluate(record, spec, frozen=frozen if frozen is not None else selected) return { "status": "ready" if view["complete"] else "blocked", "task": expected_task, @@ -204,6 +223,8 @@ def campaign_gate(path: Path, *, expected_task: str = "task-performance", "revision": record["revision"], "complete": view["complete"], "questions": view["questions"], + "brief_review": view["brief_review"], + "task_brief": view["task_brief"], "blockers": view["blockers"], "conflicts": view["conflicts"], "allowed_next": view["allowed_next"], @@ -223,6 +244,16 @@ def attach_record(session_dir: Path, record: dict, gate: dict) -> dict: }} +def _render_brief(view: dict) -> list[str]: + brief = view["task_brief"] + if not brief: + return [] + return [f"Task brief (revision {brief['revision']}, {view['brief_review']})", + f"Performance target: {brief['performance_target']}", + f"Accuracy on {brief['benchmark']}: {brief['quality_gate']}", + *(f" {key}: {value}" for key, value in brief["conditions"].items())] + + def _render_questions(view: dict) -> list[str]: lines = [] if view["questions"]: @@ -242,6 +273,7 @@ def _render_questions(view: dict) -> list[str]: def render(view: dict) -> str: lines = [f"task: {view['task']} revision: {view['revision']} " f"complete: {'true' if view['complete'] else 'false'}"] + lines.extend(_render_brief(view)) lines.extend(_render_questions(view)) if view["conflicts"]: lines.append("conflicts:") @@ -261,6 +293,7 @@ def render(view: dict) -> str: def render_summary(view: dict) -> str: lines = [f"task: {view['task']} revision: {view['revision']} " f"complete: {'true' if view['complete'] else 'false'}"] + lines.extend(_render_brief(view)) for label, values in (("confirmed", view["confirmed"]), ("proposed", view["proposed"])): if values: lines.append(f"{label}:") @@ -284,12 +317,20 @@ def render_summary(view: dict) -> str: def command(args) -> int: try: - if args.intake_action == "evaluate": - result = evaluate_command(args) - elif args.intake_action == "answer": - result = answer_command(args) - else: + if args.intake_action == "summary": result = summary_command(args) + else: + path = args.record + path.parent.mkdir(parents=True, exist_ok=True) + with file_lock(path.with_name(path.name + ".lock")): + if args.intake_action == "evaluate": + result = evaluate_command(args) + else: + result = answer_command(args) + except BlockingIOError: + print(json.dumps({"error": "record_busy", "message": "Retry after the current update", + "execution": "not started"})) + return 2 except intake.IntakeError as exc: print(json.dumps({"error": exc.code, "message": str(exc), "execution": "not started"}, ensure_ascii=False, indent=2)) diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md index 19a8b677d..09b8a16b0 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md @@ -56,6 +56,25 @@ returns. A field answered `unknown` blocks its stage instead of being asked again. Do not derive a threshold from a request such as "make it faster": the acceptance issue or frozen plan states it. +## Read back the task brief and obtain approval + +Collect the final **numeric** performance goal (absolute bound with units, or +minimum percentage improvement over the pinned baseline), performance workload +and timing boundary. Confirm the accuracy benchmark and split, metric, +comparison, numeric threshold and unit, plus the quality check and failure +policy. A candidate retention threshold alone does not specify a final target. + +When intake returns `brief_review: awaiting_confirmation`, read back the complete +`task_brief` in the user's language, including the target and accuracy +inequalities, benchmark, pinned setup, commands, scope, comparison and budget. +Then call the native question-card tool for a **separate** approve-or-revise +decision on that brief. Wait for a new explicit reply. Use `task intake answer` +with this revision's `q:task_brief:...` ID. Record requested changes, update the +fields and read back the new brief for fresh approval. Until approval, only +read-only preparation is allowed, even if the user answered every field or +selected an existing acceptance plan. Hand the approved record to `campaign +start --intake`; apply the approved conditions to the validator and final replay. + ## Run the procedure 1. Replay the supplied benchmark unchanged. Pin requests, shape/batch mix, concurrency, warmup, timing boundary, repetitions, aggregation rule and quality oracle. Capture the baseline distribution and end-to-end output on the actual engine and device. diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json index 72dddcd5c..8a419ac33 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json @@ -71,6 +71,71 @@ "question": "Which baseline revision is pinned for this round?", "required_before": ["candidate_search"] }, + { + "path": "protocol.target_kind", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "choice", + "question": "Is the final performance target an absolute metric bound or a percentage improvement over the pinned baseline?", + "options": [{"value": "absolute"}, {"value": "relative_improvement_pct"}], + "required_before": ["candidate_search"] + }, + { + "path": "protocol.target_value", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "number", + "question": "What numeric target must the final result reach, in the metric unit for an absolute bound or percent for a relative gain?", + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_benchmark", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "text", + "question": "Which fixed accuracy benchmark, version or split, reference and input set decide quality?", + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_metric", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "text", + "question": "Which accuracy metric or baseline-relative quality difference is scored?", + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_comparator", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "choice", + "question": "Which comparison must the accuracy result satisfy?", + "options": [{"value": "at_least"}, {"value": "at_most"}, {"value": "equal"}], + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_limit", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "number", + "question": "What numeric accuracy threshold or maximum regression is acceptable?", + "required_before": ["candidate_search"] + }, + { + "path": "protocol.quality_unit", + "user_choice": true, + "maps_to": "summary-only", + "batch": 1, + "type": "text", + "question": "In what units is the accuracy threshold expressed?", + "required_before": ["candidate_search"] + }, { "path": "environment.quality_command", "user_choice": true, diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index 22e478ab4..d04a783aa 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -68,15 +68,29 @@ def test_day0_fields_stay_out_of_task_input_v1(): assert all(field["maps_to"] == "day0-spec" for field in spec["fields"]) -def test_complete_record_asks_nothing_and_unlocks_search(): +def approved_record(): + record, view = ask(build(), spec_for()) + return intake.answer(record, spec_for(), question_id=view["task_brief"]["id"], value="approve") + + +def test_complete_fields_require_separate_review_before_search(): spec = spec_for() - view = intake.evaluate(build(), spec) - assert view["complete"] is True - assert view["questions"] == [] - assert view["conflicts"] == [] - assert view["allowed_next"] == [ - "read_only_preparation", "baseline_measurement", "candidate_search"] - assert view["execution"] == "not started" + record, view = ask(build(), spec) + assert view["brief_review"] == "awaiting_confirmation" + brief = view["task_brief"] + assert brief["performance_target"] == "p95_ttft <= 180 ms" + assert brief["quality_gate"] == "token mismatches <= 0 tokens" + assert brief["benchmark"] == ALL_VALUES["protocol.quality_benchmark"] + assert brief["conditions"] == ALL_VALUES + assert [q["id"] for q in view["questions"]] == [brief["id"]] + assert not view["complete"] and view["needs_user_input"] + assert view["allowed_next"] == ["read_only_preparation"] + approved = intake.evaluate(approved_record(), spec) + assert approved["complete"] and not approved["questions"] + assert approved["brief_review"] == "approved" + assert approved["allowed_next"] == ["read_only_preparation", "baseline_measurement", + "candidate_search"] + assert approved["execution"] == "not started" def test_empty_record_asks_only_the_first_batch(): @@ -225,7 +239,7 @@ def test_cli_evaluate_matches_the_python_view_and_writes_only_the_record(tmp_pat for key in ("questions", "blockers", "conflicts", "allowed_next", "complete", "execution", "revision"): assert result[key] == expected[key] - assert {path.name for path in tmp_path.iterdir()} == {"record.json"} + assert {path.name for path in tmp_path.iterdir()} == {"record.json", "record.json.lock"} def test_cli_answer_then_summary(tmp_path, capsys): @@ -276,7 +290,7 @@ def test_frozen_values_read_the_gate_task_file(): def test_matching_frozen_gate_keeps_a_complete_record_complete(): frozen = task_intake.frozen_values(PERFORMANCE / "frozen-gate.yaml") - view = intake.evaluate(build(), spec_for(), frozen=frozen) + view = intake.evaluate(approved_record(), spec_for(), frozen=frozen) assert view["conflicts"] == [] and view["complete"] is True @@ -296,11 +310,11 @@ def test_campaign_gate_blocks_until_complete(tmp_path): assert gate["status"] == "blocked" assert gate["allowed_next"] == ["read_only_preparation"] complete = tmp_path / "complete.json" - complete.write_text(json.dumps(build()), encoding="utf-8") + complete.write_text(json.dumps(approved_record()), encoding="utf-8") gate, gated = task_intake.campaign_gate(complete) assert gate["status"] == "ready" assert gate["complete"] is True - assert gated == build() + assert gated == approved_record() def test_campaign_start_refuses_an_incomplete_record_before_writing(project, tmp_path, capsys): # noqa: F811 @@ -314,13 +328,13 @@ def test_campaign_start_refuses_an_incomplete_record_before_writing(project, tmp def test_campaign_start_retains_the_record_it_gated(project, tmp_path, capsys): # noqa: F811 record = tmp_path / "record.json" - record.write_text(json.dumps(build()), encoding="utf-8") + record.write_text(json.dumps(approved_record()), encoding="utf-8") assert cli.main(start_arguments(project, extra=("--intake", str(record)))) == 0 result = json.loads(capsys.readouterr().out) retained = project[3] / "intake.json" assert result["intake"]["gate"] == "ready" assert result["intake"]["sha256"] == hashlib.sha256(retained.read_bytes()).hexdigest() - assert json.loads(retained.read_text(encoding="utf-8")) == build() + assert json.loads(retained.read_text(encoding="utf-8")) == approved_record() # The retained record does not disturb the managed campaign's own records. assert cli.main(["campaign", "status", "--directory", str(project[3])]) == 0 @@ -448,7 +462,7 @@ def test_selected_gate_imports_only_its_values_and_changed_file_reopens_card(tmp assert task_intake.campaign_gate(record)[0]["status"] == "blocked" -def test_fully_specified_request_selects_existing_gate_without_questions(tmp_path, capsys): +def test_fully_specified_request_still_needs_final_card(tmp_path, capsys): gate = PERFORMANCE / "frozen-gate.yaml" record = tmp_path / "record.json" values = {**COMPLETE["fields"]["values"], intake.REFERENCE: str(gate)} @@ -458,7 +472,12 @@ def test_fully_specified_request_selects_existing_gate_without_questions(tmp_pat args.extend(("--set", f"{key}={value}")) assert cli.main(args) == 0 result = json.loads(capsys.readouterr().out) - assert result["complete"] and not result["needs_user_input"] + assert not result["complete"] and result["needs_user_input"] + assert result["brief_review"] == "awaiting_confirmation" + assert task_intake.campaign_gate(record)[0]["status"] == "blocked" + assert cli.main(["task", "intake", "answer", "--record", str(record), "--question", + result["task_brief"]["id"], "--value", "approve", "--json"]) == 0 + assert json.loads(capsys.readouterr().out)["complete"] assert task_intake.campaign_gate(record)[0]["status"] == "ready" @@ -476,3 +495,90 @@ def test_user_can_replace_suggested_goal_and_settle_a_conflict(): assert view["questions"][0]["field"] == "optimization.objective" record = intake.answer(record, spec, question_id="q:optimization.objective", value="latency") assert record["fields"]["optimization.objective"]["status"] == "confirmed" + +@pytest.mark.parametrize("path", ["protocol.target_value", "protocol.quality_limit", + "protocol.quality_benchmark", "protocol.quality_unit"]) +def test_numeric_targets_and_benchmark_require_user_selection(path): + spec = spec_for() + record = build(set(ALL_VALUES) - {path}) + record = intake.set_fields(record, spec, {path: ALL_VALUES[path]}, source="repo_inspection") + view = intake.evaluate(record, spec) + assert [q["field"] for q in view["questions"]] == [path] + assert view["task_brief"] is None + assert view["allowed_next"] == ["read_only_preparation"] + + +def test_brief_answer_must_match_the_current_issued_revision(): + spec = spec_for() + original = build() + original["fields"]["protocol.target_value"]["value"] = 12 + record, view = ask(original, spec) + review = view["task_brief"]["id"] + with pytest.raises(intake.IntakeError): + intake.answer(build(), spec, question_id=review, value="approve") + with pytest.raises(intake.IntakeError): + intake.answer(record, spec, question_id=review, value="yes by default") + changed = intake.set_fields(record, spec, {"protocol.target_kind": "relative_improvement_pct"}, + source="prompt") + with pytest.raises(intake.IntakeError): + intake.answer(changed, spec, question_id=review, value="approve") + changed, _ = ask(changed, spec) + changed = intake.answer(changed, spec, question_id="q:protocol.target_kind", + value="relative_improvement_pct") + changed, next_view = ask(changed, spec) + assert "12%" in next_view["task_brief"]["performance_target"] + assert next_view["task_brief"]["id"] != review + assert next_view["brief_review"] == "awaiting_confirmation" + assert intake.answer(changed, spec, question_id=next_view["task_brief"]["id"], + value="approve")["brief_decision"]["value"] == "approve" + + +@pytest.mark.parametrize("reply", [{"value": "revise"}, {"unknown": True}]) +def test_returned_brief_waits_for_edits_then_requires_new_review(reply): + spec = spec_for() + record, view = ask(build(), spec) + record = intake.answer(record, spec, question_id=view["task_brief"]["id"], **reply) + view = intake.evaluate(record, spec) + assert not view["complete"] and not view["questions"] + assert view["brief_review"] == "changes_requested" + with pytest.raises(intake.IntakeError): + intake.answer(record, spec, question_id=view["task_brief"]["id"], value="approve") + edited = intake.set_fields(record, spec, {"protocol.quality_limit": 2}, source="prompt") + edited, _ = ask(edited, spec) + edited = intake.answer(edited, spec, question_id="q:protocol.quality_limit", value=2) + assert intake.evaluate(edited, spec)["brief_review"] == "awaiting_confirmation" + + +def test_campaign_checks_live_gate_and_exact_brief(project, tmp_path, capsys): # noqa: F811 + gate = tmp_path / "gate.yaml" + gate.write_bytes((PERFORMANCE / "frozen-gate.yaml").read_bytes()) + path = tmp_path / "record.json" + args = ["task", "intake", "evaluate", "--task", "task-performance", "--record", + str(path), "--frozen", str(gate), "--json"] + for key, value in (COMPLETE["fields"]["values"] | {intake.REFERENCE: str(gate)}).items(): + args.extend(("--set", f"{key}={value}")) + assert cli.main(args) == 0 + brief = json.loads(capsys.readouterr().out)["task_brief"] + assert cli.main(start_arguments(project, extra=("--intake", str(path)))) == 2 + assert json.loads(capsys.readouterr().out)["brief_review"] == "awaiting_confirmation" + assert not project[3].exists() + assert cli.main(["task", "intake", "answer", "--record", str(path), "--question", + brief["id"], "--value", "approve", "--json"]) == 0 + assert json.loads(capsys.readouterr().out)["complete"] + gate.write_bytes((PERFORMANCE / "frozen-mismatch.yaml").read_bytes()) + assert cli.main(start_arguments(project, extra=("--intake", str(path)))) == 2 + assert json.loads(capsys.readouterr().out)["brief_review"] == "collecting_inputs" + assert not project[3].exists() + + +def test_old_or_modified_record_cannot_reuse_a_cached_approval(tmp_path): + path = tmp_path / "record.json" + record = approved_record() + record["fields"]["environment.rounds"]["value"] += 1 + path.write_text(json.dumps(record)) + assert task_intake.campaign_gate(path)[0]["brief_review"] == "awaiting_confirmation" + record.pop("brief_decision") + del record["fields"]["protocol.target_value"] + record["complete"] = True + path.write_text(json.dumps(record)) + assert task_intake.campaign_gate(path)[0]["brief_review"] == "collecting_inputs" diff --git a/tests/fixtures/intake/performance/complete.json b/tests/fixtures/intake/performance/complete.json index 99e908191..648c109dc 100644 --- a/tests/fixtures/intake/performance/complete.json +++ b/tests/fixtures/intake/performance/complete.json @@ -1,6 +1,6 @@ { "task": "task-performance", - "description": "A complete task-performance intake record: every field the spec asks for is stated, so evaluate returns no questions.", + "description": "All field decisions are supplied. A separate reply must approve the task brief.", "fields": { "source": "prompt", "values": { @@ -22,7 +22,14 @@ "environment.rounds": 4, "protocol.timing_boundary": "server-side, includes queueing but not client transfer", "protocol.comparison": "abba", - "protocol.quality_failure_policy": "revert_candidate" + "protocol.quality_failure_policy": "revert_candidate", + "protocol.target_kind": "absolute", + "protocol.target_value": 180, + "protocol.quality_benchmark": "fixed-prompts-v1, held-out split", + "protocol.quality_metric": "token mismatches", + "protocol.quality_comparator": "at_most", + "protocol.quality_limit": 0, + "protocol.quality_unit": "tokens" } }, "acceptance": { From de7977d7dac0088cf7134af7e182db691f686f89 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 13:07:41 +0800 Subject: [PATCH 07/26] Refresh generated skill indexes for task brief review Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/searchspace-index.json | 2 +- docs/skill-coverage.md | 2 +- .../knowledge/data/skill_library/_compiled/_provenance.json | 2 +- .../knowledge/data/skill_library/_compiled/inputs.json | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index b1bce6512..ee51ea8c5 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -6,7 +6,7 @@ "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "0b0032869e4e437357898c2ab956d1ec8497aa4b2f9a76880684db9fd66dae05" + "metadata_sha256": "67d7ff2d455e4031ffd7178d667b2f254812b05f93eef5be69773346d57f074e" }, "skills": { "ascend-aclgraph-capture-replay": {"path": "systems/platforms/ascend/ascend-aclgraph-capture-replay/SKILL.md", "state": "covered", "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], ["Accelerator", "Optimize"], ["Accelerator", "Verify"]]}, diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index 53ed28bcb..89291cbca 100644 --- a/docs/skill-coverage.md +++ b/docs/skill-coverage.md @@ -4,7 +4,7 @@ Generated from the registry, SKILL.md frontmatter and the two maintained matrices. **Do not edit by hand**; regenerate after any registry, skill, matrix or frozen-plan change. -- Input digest: `sha256:d44b87d8f3a7619032c0b145e6657e3245b01bd3b12348295ec9795c95943770` +- Input digest: `sha256:ef7131b8682d71672c62af103e4c2e7344198c6ba0035a336b43821b1874d48c` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 8337d9630..bb6b7d531 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "9bbbf4edf45a0d793c969f9bc9d85d901f7c22e5", + "source_revision": "e4cab3fc2abdbeb5f7faead828efe8a398b72fa1", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index 755894cb2..e5825d056 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -1205,8 +1205,8 @@ "description": "Use when a correct inference baseline misses a latency, throughput, memory or cost target. Compare compatible changes under the user's workload and quality gate." }, "files": { - "SKILL.md": "2fc9b33415ae51cbb9ef8c1135afa8512f19693fd0d157069d9312dbe5eabea2", - "intake.json": "e91cebd1f3dbe5aec9f41ceebbefdfc56a73e17b3c139af925537d06817ceda7" + "SKILL.md": "cf90e10f1cc101efa4fd4aa5689bf78992a86466354809ada078b2363837ea20", + "intake.json": "13ecae20885d7ea07bbb00b84be3481f4a825590e2e4044abd6cdb2d6bcaf680" } }, "task-version-alignment": { From f3c427b86eed33d724dd25745b7590b920389f4a Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 13:11:39 +0800 Subject: [PATCH 08/26] Preserve threshold precision and reselect gates during brief revision Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 6 +++++- src/inferrsi/apps/cli/intake_contract.py | 9 ++++---- src/inferrsi/apps/cli/task_intake.py | 17 +++++++++++++--- tests/apps/test_task_intake.py | 26 ++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 8 deletions(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 2f571de04..f1aeb3328 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -158,7 +158,11 @@ inferrsi task intake answer --record --question dict: values = {field["path"]: _coerce(field, record["fields"][field["path"]]["value"]) for field in spec["fields"] if _applicable(record, field)} metric = values["acceptance.metric_key"] - target = values["protocol.target_value"] + target = str(values["protocol.target_value"]).removesuffix(".0") if values["protocol.target_kind"] == "relative_improvement_pct": - performance = f"{metric}: improve by at least {target:g}% over the pinned baseline" + performance = f"{metric}: improve by at least {target}% over the pinned baseline" else: comparison = "<=" if values["acceptance.direction"] == "minimize" else ">=" - performance = f"{metric} {comparison} {target:g} {values['acceptance.metric_unit']}" + performance = f"{metric} {comparison} {target} {values['acceptance.metric_unit']}" operators = {"at_least": ">=", "at_most": "<=", "equal": "="} operator = operators[values["protocol.quality_comparator"]] + limit = str(values["protocol.quality_limit"]).removesuffix(".0") quality = (f"{values['protocol.quality_metric']} {operator} " - f"{values['protocol.quality_limit']:g} {values['protocol.quality_unit']}") + f"{limit} {values['protocol.quality_unit']}") brief = {"record_id": record["record_id"], "revision": record["revision"], "task": record["task"], "performance_target": performance, "quality_gate": quality, "benchmark": values["protocol.quality_benchmark"], "conditions": values} diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 103bd89ce..4f39a0fc9 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -176,13 +176,24 @@ def evaluate_command(args) -> dict: record = intake.reconcile_record(record, spec) values = parse_sets(args.set) selecting = intake.REFERENCE in values and args.source in ("prompt", "grilling_brief") + bind_file = selecting and not existing if existing and selecting and intake.selected_reference(record) != values[intake.REFERENCE]: - raise intake.IntakeError("user_answer_required", - "Use the acceptance reference question to record the user's reply") + if intake.evaluate(record, spec)["brief_review"] != "changes_requested": + raise intake.IntakeError("user_answer_required", + "Use the reference question to record the user's reply") + # An explicit correction to a returned brief replaces the reference. Values + # sourced from its former authority must be obtained from the new selection. + previous = intake.selected_reference(record) + record["fields"] = {key: entry for key, entry in record["fields"].items() + if key != intake.REFERENCE and not ( + previous and entry.get("authority_reference") == previous)} + record.pop("selected_gate", None) + record.pop("selected_gate_file", None) + bind_file = True if values: record = intake.set_fields(record, spec, values, source=args.source) return _evaluate_and_save(record_path, record, spec, args.frozen, - selecting_reference=selecting and not existing) + selecting_reference=bind_file) def answer_command(args) -> dict: diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index d04a783aa..bd79f8a32 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -582,3 +582,29 @@ def test_old_or_modified_record_cannot_reuse_a_cached_approval(tmp_path): record["complete"] = True path.write_text(json.dumps(record)) assert task_intake.campaign_gate(path)[0]["brief_review"] == "collecting_inputs" + + +def test_brief_displays_the_full_precision_of_both_thresholds(): + record = build() + for path in ("protocol.target_value", "protocol.quality_limit"): + record["fields"][path]["value"] = 0.123456789 + brief = intake.evaluate(record, spec_for())["task_brief"] + assert brief["performance_target"] == "p95_ttft <= 0.123456789 ms" + assert brief["quality_gate"] == "token mismatches <= 0.123456789 tokens" + + +def test_user_can_choose_a_different_gate_after_returning_the_brief(tmp_path, capsys): + path = tmp_path / "intake.json" + record, view = ask(build(), spec_for()) + path.write_text(json.dumps(record)) + assert cli.main(["task", "intake", "answer", "--record", str(path), "--question", + view["task_brief"]["id"], "--value", "revise", "--json"]) == 0 + assert json.loads(capsys.readouterr().out)["brief_review"] == "changes_requested" + gate = PERFORMANCE / "frozen-mismatch.yaml" + assert cli.main(["task", "intake", "evaluate", "--record", str(path), "--set", + f"{intake.REFERENCE}={gate}", "--frozen", str(gate), "--json"]) == 0 + updated = json.loads(capsys.readouterr().out) + assert updated["fields"]["acceptance.metric_key"]["value"] == "p99_ttft" + assert updated["fields"]["acceptance.metric_key"]["source"] == "frozen_gate" + assert updated["brief_review"] == "awaiting_confirmation" + assert updated["task_brief"]["id"] != view["task_brief"]["id"] From 0670dd10d3e062c94ac1cd1cdf83e69403a98ff1 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 13:27:23 +0800 Subject: [PATCH 09/26] Register the intake CLI as a consumer of the Apps file lock Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/apps-module-migrations.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 9256effd3..9d8fa32ff 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -585,6 +585,7 @@ "docs/guides/skill-evaluation/local-skill-evaluation.md", "examples/qwen21_turbo_b300.py", "examples/qwen21_turbo_quality.py", + "src/inferrsi/apps/cli/task_intake.py", "src/inferrsi/apps/delivery/__init__.py", "src/inferrsi/apps/delivery/projection.py", "src/inferrsi/apps/delivery/snapshot.py", From cebe9271fea2f0af4ba20075e63a5b3ca8c41eb9 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 14:42:58 +0800 Subject: [PATCH 10/26] Resolve intake card conflicts and validate execution bounds before review Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 10 ++- src/inferrsi/apps/cli/intake_contract.py | 75 ++++++++++++------- src/inferrsi/apps/cli/task_input.py | 8 +- src/inferrsi/apps/cli/task_intake.py | 1 + tests/apps/test_task_intake.py | 95 ++++++++++++++++++++++++ 5 files changed, 159 insertions(+), 30 deletions(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index f1aeb3328..6417d68d5 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -101,7 +101,9 @@ blocks candidate search. 1. Ask applicable missing fields and unconfirmed suggestions. Return the suggested value and its source as an option. Preserve a user’s explicit unknown answer until new confirmed information arrives. 2. A conflicting field is asked before anything else; its options are the - recorded candidate values with their sources. + recorded candidate values with their sources. Answering the card selects one + value and clears the other options. An acceptance choice stays proposed until + the selected authority confirms it. A differing issue value reopens the choice. 3. Otherwise the lowest missing `batch` is asked as one batch. Answers to other batches wait until earlier batches settle. 4. `unknown` is a recorded answer: the field is not asked again, and it blocks @@ -135,6 +137,12 @@ presented later, or its acceptance contents change, evaluating it reopens the reference question. Conflicting metric values remain visible. Reconfirm the file and resolve conflicting proposals with the user before search. +For mapped numeric fields, intake uses the task-input/v1 bounds. Repetitions +and rounds must be positive integers, the time budget must be positive and at +most seven days, and the minimum improvement percentage must be nonnegative. +Invalid replies leave the question open. Older records with out-of-range values +reopen those questions and require a fresh brief approval after correction. + ## Final performance brief A final goal has a metric, direction and numeric target. For an absolute diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index 0b0aa8489..d35115003 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -7,7 +7,7 @@ next stage, derives ``allowed_next`` and never authenticates acceptance thresholds: a proposal kept in a record does not freeze a gate. -Nothing here performs I/O or imports another InferRSI module. Callers in +The contract performs no I/O. Mapped numeric values use the task-input validator. Callers in ``inferrsi.apps.cli.task_intake`` load the versioned spec and record, then call these pure functions. ``source`` is declared by the caller and is not authenticated. """ @@ -19,6 +19,8 @@ import json import math +from . import task_input + SCHEMA_VERSION = 1 # Stage vocabulary. ``read_only_preparation`` is always allowed; the others are @@ -98,6 +100,9 @@ def bad(path: str, message: str) -> None: seen.add(path) if field.get("maps_to") not in MAP_TARGETS: bad(f"{where}.maps_to", f"must be one of {', '.join(MAP_TARGETS)}") + if (field.get("maps_to") == "task-input/v1" and field.get("type") in ("integer", "number") + and isinstance(path, str) and path not in task_input.BY_PATH): + bad(f"{where}.path", f"{path} is not a task-input/v1 field") if not isinstance(field.get("question"), str) or not field["question"].strip(): bad(f"{where}.question", "must be a non-empty string") batch = field.get("batch", 1) @@ -210,7 +215,7 @@ def bad(field: str, message: str) -> None: bad(path, "source must be a string") if entry.get("status") in SETTLED: try: - _coerce(known[path], entry.get("value")) + _typed_value(known[path], entry.get("value")) except IntakeError as exc: bad(path, str(exc)) if type(entry.get("asked", False)) is not bool: @@ -234,20 +239,18 @@ def _settled(record: dict, path: str) -> bool: return _entry(record, path).get("status") in SETTLED -def _coerce(field: dict, value: object) -> object: +def _typed_value(field: dict, value: object) -> object: kind = field.get("type", "text") if kind == "number": - number = value - if isinstance(value, bool) or not isinstance(value, (int, float)): - number = None - if isinstance(value, str): - try: - number = float(value) - except ValueError: - number = None - if number is None or not math.isfinite(float(number)): + if isinstance(value, bool) or not isinstance(value, (str, int, float)): raise IntakeError("invalid_value", f"{field['path']} must be a finite number") - return float(number) + try: + number = float(value) + except (OverflowError, ValueError) as exc: + raise IntakeError("invalid_value", f"{field['path']} must be a finite number") from exc + if not math.isfinite(number): + raise IntakeError("invalid_value", f"{field['path']} must be a finite number") + return number if kind == "integer": if type(value) is int: return value @@ -268,6 +271,16 @@ def _coerce(field: dict, value: object) -> object: return value +def _coerce(field: dict, value: object) -> object: + typed = _typed_value(field, value) + if field["maps_to"] == "task-input/v1" and field.get("type") in ("integer", "number"): + mapped = task_input.BY_PATH[field["path"]] + problem = task_input.field_value_problem(mapped, typed) + if problem: + raise IntakeError("invalid_value", f"{mapped.path} {problem}") + return typed + + def _user_source(path: str, source: str) -> bool: return source in ("prompt", "grilling_brief") or source == f"answer:{_QUESTION}{path}" @@ -309,10 +322,25 @@ def reconcile_record(record: dict, spec: dict) -> dict: _check(record, spec) updated = copy.deepcopy(record) fields = _field_paths(spec) + reopened = False for path, entry in updated["fields"].items(): if entry["status"] in ("confirmed", "proposed", "assumed"): + field = fields[path] + if field.get("type") in ("integer", "number"): + try: + _coerce(field, entry.get("value")) + except IntakeError: + # Older intakes accepted out-of-range execution values. Keep their + # provenance and reissue the field question before another brief. + updated["fields"][path] = {"value": None, "status": "unknown", + "source": entry["source"], + "rejected_value": entry.get("value")} + reopened = True + continue bound = _bound_value(record, path, entry) - entry["status"] = _status_for(fields[path], entry["source"], bound=bound) + entry["status"] = _status_for(field, entry["source"], bound=bound) + if reopened: + _bump(updated, updated["revision"] + 1) return updated @@ -363,19 +391,16 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: continue if (current is not None and current.get("status") == "conflicting" and isinstance(current.get("candidates"), list)): - candidates = [item for item in current["candidates"] if item["value"] != value] - candidates.append({"value": value, "source": source}) - if len({_canonical(item["value"]) for item in candidates}) == 1: - updated["fields"][path] = entry - else: - updated["fields"][path] = {"value": None, "source": source, - "status": "conflicting", - "candidates": candidates} - changed = True + # Only an explicit answer settles an open choice. Repeated imports + # can supply another option but cannot reselect one on the user's behalf. + if all(item["value"] != value for item in current["candidates"]): + current["candidates"].append({"value": value, "source": source}) + changed = True continue if (current is not None and current.get("status") not in (None, "unknown") and current.get("value") is not None and current.get("value") != value): - if _rank(status) > _rank(current["status"]): + disagrees_with_answer = bound and current.get("source") == f"answer:{_QUESTION}{path}" + if _rank(status) > _rank(current["status"]) and not disagrees_with_answer: updated["fields"][path] = entry changed = True elif _rank(status) < _rank(current["status"]): @@ -710,7 +735,7 @@ def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: "schema_version": SCHEMA_VERSION, "task": spec["task"], "record_id": record["record_id"], - "revision": record["revision"], + "revision": view["revision"], "primary_task": record["primary_task"], "phase": record["phase"], "task_brief": view["task_brief"], diff --git a/src/inferrsi/apps/cli/task_input.py b/src/inferrsi/apps/cli/task_input.py index 7f5b3f8c0..613056ba4 100644 --- a/src/inferrsi/apps/cli/task_input.py +++ b/src/inferrsi/apps/cli/task_input.py @@ -208,7 +208,7 @@ def _http_url(value: str) -> str | None: return None -def _check(field: Field, value: object) -> str | None: +def field_value_problem(field: Field, value: object) -> str | None: """Return why ``value`` (never None) is invalid for ``field``, or None.""" if not _encodable(value): return "must be valid Unicode text" @@ -317,7 +317,7 @@ def validate(data: object) -> list[dict[str, str]]: if field is None: errors.append(_error(f"{section}.{name}", "is not a v1 task field")) elif value is not None: - problem = _check(field, value) + problem = field_value_problem(field, value) if problem: errors.append(_error(field.path, problem)) return errors @@ -470,7 +470,7 @@ def merge( raw = values.get(field.name) if isinstance(values, dict) else None if field.section in sections and not isinstance(values, dict): value, source = None, "invalid" - elif raw is not None and _check(field, raw) is None: + elif raw is not None and field_value_problem(field, raw) is None: value, source = _normalize(field, raw, base), "yaml" elif raw is not None: value, source = None, "invalid" @@ -481,7 +481,7 @@ def merge( supplied = overrides.pop(field.dest, None) if field.dest else None if supplied is not None: # None means the caller did not supply the flag supplied = _flag_value(field, supplied) - problem = _check(field, supplied) + problem = field_value_problem(field, supplied) if problem: errors.append(_error(field.path, f"{field.flag} {problem}", "cli")) elif field.acceptance: diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 4f39a0fc9..d677a852e 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -225,6 +225,7 @@ def campaign_gate(path: Path, *, expected_task: str = "task-performance", raise intake.IntakeError( "task_mismatch", f"{path} records {record.get('task')}, not {expected_task}") spec = load_spec(expected_task) + record = intake.reconcile_record(record, spec) record, selected = _evaluate_gate(record, spec, None, selecting_reference=False) view = intake.evaluate(record, spec, frozen=frozen if frozen is not None else selected) return { diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index bd79f8a32..88221e8e4 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -197,6 +197,47 @@ def test_two_stated_values_become_a_question_with_both_options(): assert values == {"p95_ttft", "p99_ttft"} +@pytest.mark.parametrize("selected", ["p95_ttft", "p99_ttft"]) +def test_metric_conflict_card_then_matching_issue_confirmation(tmp_path, capsys, selected): + path = tmp_path / "intake.json" + record = ["--record", str(path), "--json"] + metric = "acceptance.metric_key" + reference = "selected acceptance issue" + + def call(*args): + assert cli.main(["task", "intake", *args, *record]) == 0 + return json.loads(capsys.readouterr().out) + + call("evaluate", "--task", "task-performance", "--set", f"{intake.REFERENCE}={reference}", + "--set", f"{metric}=p95_ttft") + view = call("evaluate", "--set", f"{metric}=p99_ttft") + card = view["questions"][0] + assert card["field"] == metric + assert {opt["value"] for opt in card["options"]} == {"p95_ttft", "p99_ttft"} + assert call("evaluate", "--set", f"{metric}={selected}")["revision"] == view["revision"] + chosen = call("answer", "--question", card["id"], "--value", selected) + assert chosen["fields"][metric] == {"value": selected, "source": f"answer:q:{metric}", + "status": "proposed"} + assert not any(q["field"] == metric for q in chosen["questions"]) + issue = call("evaluate", "--source", "issue", "--set", f"{metric}={selected}", + "--set", f"{intake.REFERENCE}={reference}") + assert issue["fields"][metric] == {"value": selected, "source": "issue", "status": "confirmed"} + assert not issue["complete"] + + +def test_mismatching_issue_reopens_an_explicit_card_choice(): + spec = spec_for() + record = build({intake.REFERENCE}) + record, _ = ask(record, spec) + key = "acceptance.metric_key" + record = intake.answer(record, spec, question_id=f"q:{key}", value="p95_ttft") + record = intake.set_fields(record, spec, {key: "p99_ttft", intake.REFERENCE: + ALL_VALUES[intake.REFERENCE]}, source="issue") + view = intake.evaluate(record, spec) + assert view["fields"][key]["status"] == "conflicting" + assert {x["value"] for x in view["questions"][0]["options"]} == {"p95_ttft", "p99_ttft"} + + def test_frozen_gate_mismatch_blocks_candidate_search(): spec = spec_for() frozen = {"acceptance.metric_key": "p99_ttft"} @@ -608,3 +649,57 @@ def test_user_can_choose_a_different_gate_after_returning_the_brief(tmp_path, ca assert updated["fields"]["acceptance.metric_key"]["source"] == "frozen_gate" assert updated["brief_review"] == "awaiting_confirmation" assert updated["task_brief"]["id"] != view["task_brief"]["id"] + +@pytest.mark.parametrize(("key", "invalid", "valid"), [ + ("environment.repetitions", 0, 1), + ("environment.rounds", -1, 1), + ("environment.max_minutes", -5, 0.5), + ("environment.max_minutes", 10081, 10080), + ("acceptance.min_improvement_pct", -1, 0), +]) +def test_execution_bounds_apply_to_set_and_open_card(tmp_path, capsys, key, invalid, valid): + path = tmp_path / "intake.json" + record = ["--record", str(path), "--json"] + path.write_text(json.dumps(build(set(ALL_VALUES) - {key}))) + assert cli.main(["task", "intake", "evaluate", *record]) == 0 + view = json.loads(capsys.readouterr().out) + question = next(q for q in view["questions"] if q["field"] == key) + unchanged = path.read_bytes() + for cmd in (["evaluate", "--set", f"{key}={invalid}"], + ["answer", "--question", question["id"], "--value", str(invalid)]): + assert cli.main(["task", "intake", *cmd, *record]) == 2 + error = json.loads(capsys.readouterr().out) + assert error["error"] == "invalid_value" and key in error["message"] + assert path.read_bytes() == unchanged + assert cli.main(["task", "intake", "answer", "--question", question["id"], + "--value", str(valid), *record]) == 0 + assert json.loads(capsys.readouterr().out)["fields"][key]["value"] == valid + + +def test_loaded_approved_record_reopens_unusable_execution_values(project, tmp_path, capsys): # noqa: F811 + path = tmp_path / "intake.json" + record = approved_record() + invalid = {"environment.repetitions": 0, "environment.rounds": -1, + "environment.max_minutes": -5} + for key, value in invalid.items(): + record["fields"][key]["value"] = value + record["complete"] = True + path.write_text(json.dumps(record)) + assert cli.main(start_arguments(project, extra=("--intake", str(path)))) == 2 + gate = json.loads(capsys.readouterr().out) + assert gate["status"] == "blocked" and gate["task_brief"] is None + assert gate["allowed_next"] == ["read_only_preparation"] + assert not project[3].exists() + + cmd = ["task", "intake", "evaluate", "--record", str(path), "--json"] + assert cli.main(cmd) == 0 + reopened = json.loads(capsys.readouterr().out) + assert all(reopened["fields"][key]["status"] == "unknown" for key in invalid) + assert "brief_decision" not in json.loads(path.read_text()) + assert reopened["revision"] > record["revision"] + for key in ("environment.repetitions", "environment.max_minutes", "environment.rounds"): + assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", + "--question", f"q:{key}", "--value", "1"]) == 0 + view = json.loads(capsys.readouterr().out) + assert view["brief_review"] == "awaiting_confirmation" + assert not view["complete"] From 6f5775d29d3546732113900ef811d60a5943aa62 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 15:38:04 +0800 Subject: [PATCH 11/26] Describe executable brief preparation and the final approval card Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- .../optimization-workflow-unification.md | 4 +- docs/guides/service-reuse-campaigns.md | 5 ++- docs/guides/task-intake.md | 37 +++++++++++++------ plugins/inferrsi/skills/inferrsi/SKILL.md | 6 +++ .../tasks/task-performance/SKILL.md | 6 +++ 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 09d2465f9..d08a7b007 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -170,8 +170,10 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 下面是命令结构;尖括号是需要落实的项目条件,不是可直接执行的默认值。命令以 argv 执行,不经 shell;Windows 命令参数中的路径建议用正斜杠。 +Prepare the executable brief and obtain the final card reply as described in [task intake](task-intake.md#campaign-hand-off). + ```bash -inferrsi campaign start --directory \ +inferrsi campaign start --intake --directory \ --repo --include --include \ --protocol --instructions \ --measure-command '"{python}" "{protocol}/measure.py" --project "{candidate}" --result "{result}"' \ diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 0848b32ff..cfe8f8b34 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -116,8 +116,10 @@ Use `campaign start --help` for shared budget/input arguments. In service mode supply `--evaluation-config ` and omit the AB/BA single-metric, quality-command and sampling flags. Mixing both parameter sets is an error. +Prepare the executable brief and confirm the final card using the [campaign hand-off](task-intake.md#campaign-hand-off). + ```text -inferrsi campaign start --evaluation-mode service_reuse --evaluation-config ... +inferrsi campaign start --intake --evaluation-mode service_reuse --evaluation-config ... inferrsi campaign baseline --session inferrsi campaign diagnose --session --bottleneck --evidence inferrsi campaign knowledge --session --query --context-bytes @@ -271,6 +273,7 @@ version shown in `recorded_runtime_version`. ## Records, compatibility and validation +The separate intake receipt in `plan/` identifies the approved brief. Plan schema 3/state schema 2 are specific to service reuse. Missing mode means legacy AB/BA; old plans are not converted. Legacy sessions still require their recorded runtime for resume. This mode stores commit records, configuration values, ownership/run IDs and raw evidence without calculating, diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 6417d68d5..e3e28471e 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -177,21 +177,36 @@ Evaluation and summary alone cannot grant approval. Measured work requires ## Campaign hand-off +For an executable campaign, prepare the complete launch before presenting the +final card. Pass the same project, protocol and budget options to both commands. + ```text +inferrsi campaign start ... --intake --prepare-intake +# Read back the returned task_brief, including campaign_launch. Wait for the user's card reply. +inferrsi task intake answer --record --question --value approve inferrsi campaign start ... --intake ``` -`campaign start` evaluates the record for `task-performance` before writing any -plan. A blocked record prints the gate payload and exits `2`; nothing is -created. A ready record is written to `intake.json` in the campaign directory -and its sha256 is returned in the start result. Without `--intake`, start -prints a warning to stderr that the gate was not evaluated and proceeds as -before. - -The gate rechecks a selected local gate snapshot and the current brief decision. -The caller must supply campaign flags and validators matching the approved brief, -including its final target and accuracy bound. The retained intake digest is -returned with the start result. +Preparation stages the inputs in a temporary directory, compares them with the +intake and returns an executable brief. It starts no campaign or measurements. +The final approval binds the effective settings, including defaults, candidate +inputs, commands, sampling, budget and the evaluation configuration. Running +preparation again with the same settings preserves an existing approval. A +changed launch needs a fresh card. Planning-only briefs can still be reviewed. + +Start rechecks the selected gate and the approved launch before creating the +campaign. Missing, stale and mismatched approval exits with status 2. A matching +preapproval starts unattended. The frozen `plan.json` references a receipt in +`plan/` with the SHA-256 and revision of the retained `intake.json`. + +For AB/BA the two approved measurement commands describe the same script with +the candidate path supplied at execution. The quality command returns its +boolean acceptance key and a numeric result under the approved quality metric +(JSON dotted paths are supported). A boolean metric on the acceptance key is +compared as 1 or 0. The independent final checks the approved absolute bound or +relative improvement against the pinned baseline. For service reuse, the first +ranked objective names the final metric and the configuration supplies its +dataset, score key, threshold or allowed degradation, commands and sampling. ## Cards and text fallback diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index 17197b16d..bee9a8c2c 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -105,6 +105,12 @@ comparison, numeric tolerance and unit. A script name, "faster", "no quality loss", and a per-candidate retention default leave decisions open. A selected plan can supply explicit criteria; show them to the user in the brief. +For a measured campaign, prepare the intended invocation **before** the final +card: run `campaign start --prepare-intake --intake ` with the +actual launch options. Resolve any reported mismatch. Include the returned +`task_brief.campaign_launch` settings in the read-back. Preparation starts no +measurements. A planning-only brief can be reviewed without a launch. + When `brief_review` becomes `awaiting_confirmation`, read back the **complete task brief** in the user's language. Include the performance and accuracy inequalities, both benchmark inputs, baseline, model/device, timing and diff --git a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md index 09b8a16b0..9216d73ba 100644 --- a/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md @@ -64,6 +64,12 @@ and timing boundary. Confirm the accuracy benchmark and split, metric, comparison, numeric threshold and unit, plus the quality check and failure policy. A candidate retention threshold alone does not specify a final target. +For a measured campaign, prepare the intended invocation **before** the final +card: run `campaign start --prepare-intake --intake ` with the +actual launch options. Resolve any reported mismatch. Include the returned +`task_brief.campaign_launch` settings in the read-back. Preparation starts no +measurements. A planning-only brief can be reviewed without a launch. + When intake returns `brief_review: awaiting_confirmation`, read back the complete `task_brief` in the user's language, including the target and accuracy inequalities, benchmark, pinned setup, commands, scope, comparison and budget. From c80959595141ba5b1d3cfd3824fc1edcfdf00764 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 15:39:50 +0800 Subject: [PATCH 12/26] Require reviewed execution settings before starting performance campaigns Compare the staged AB/BA or service plan with the approved brief before creating the session. Freeze the receipt and enforce the numerical quality and independent final gates. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/apps-module-migrations.json | 1 + docs/searchspace-index.json | 2 +- docs/skill-coverage.md | 2 +- src/inferrsi/apps/cli/__init__.py | 27 +-- src/inferrsi/apps/cli/arguments.py | 2 + src/inferrsi/apps/cli/campaign_intake.py | 179 ++++++++++++++++++ src/inferrsi/apps/cli/intake_contract.py | 2 + src/inferrsi/apps/cli/task_intake.py | 15 +- src/inferrsi/harness/optimization_session.py | 12 +- src/inferrsi/harness/project.py | 37 +++- src/inferrsi/harness/project_service.py | 21 +- .../skill_library/_compiled/_provenance.json | 2 +- .../data/skill_library/_compiled/inputs.json | 2 +- .../test_engineering_benchmark_plugins.py | 4 +- tests/apps/test_project_explanation.py | 5 +- tests/apps/test_project_optimization.py | 8 +- tests/apps/test_project_service_reuse.py | 27 ++- tests/apps/test_task_intake.py | 103 +++++++++- tests/fixtures/campaign_intake.py | 126 ++++++++++++ tests/fixtures/service_reuse.py | 5 +- 20 files changed, 535 insertions(+), 47 deletions(-) create mode 100644 src/inferrsi/apps/cli/campaign_intake.py create mode 100644 tests/fixtures/campaign_intake.py diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 9d8fa32ff..1104bc0cc 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -585,6 +585,7 @@ "docs/guides/skill-evaluation/local-skill-evaluation.md", "examples/qwen21_turbo_b300.py", "examples/qwen21_turbo_quality.py", + "src/inferrsi/apps/cli/campaign_intake.py", "src/inferrsi/apps/cli/task_intake.py", "src/inferrsi/apps/delivery/__init__.py", "src/inferrsi/apps/delivery/projection.py", diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index ee51ea8c5..a897dd6d6 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -6,7 +6,7 @@ "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "67d7ff2d455e4031ffd7178d667b2f254812b05f93eef5be69773346d57f074e" + "metadata_sha256": "fb1f0510dc77db12b240ee9030e90eef95e7c97e3f24071decd37d24c17b5a55" }, "skills": { "ascend-aclgraph-capture-replay": {"path": "systems/platforms/ascend/ascend-aclgraph-capture-replay/SKILL.md", "state": "covered", "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], ["Accelerator", "Optimize"], ["Accelerator", "Verify"]]}, diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index 89291cbca..c1850256a 100644 --- a/docs/skill-coverage.md +++ b/docs/skill-coverage.md @@ -4,7 +4,7 @@ Generated from the registry, SKILL.md frontmatter and the two maintained matrices. **Do not edit by hand**; regenerate after any registry, skill, matrix or frozen-plan change. -- Input digest: `sha256:ef7131b8682d71672c62af103e4c2e7344198c6ba0035a336b43821b1874d48c` +- Input digest: `sha256:f3e30fec6b9e63c740c60eafe545c7032654e844c9d4a021715f55e028bceb75` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 97ec7ee37..bea5d8991 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -32,7 +32,7 @@ def _round_provider(plan): return round_provider(plan) -def _optimization_session(args, *, task_source=None, report_metadata=None): +def _optimization_session(args, *, task_source=None, report_metadata=None, initialize=None): from ...harness.optimization_session import session_command from ...knowledge.ranking_policy import managed_ranking_policy @@ -51,7 +51,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, external_knowledge=settings, external_project=external_project, external_provider_for=_round_provider, - report_metadata=report_metadata, + report_metadata=report_metadata, initialize=initialize, ) @@ -870,24 +870,15 @@ def main(argv: list[str] | None = None) -> int: if getattr(args, "session_action", None) is not None: from ..delivery import after_final - gate = None - intake_record = getattr(args, "intake", None) if args.session_action == "start" and getattr(args, "project_task", False): - from .task_intake import attach_record, campaign_gate + from .campaign_intake import start - if intake_record is not None: - gate, gated_record = campaign_gate(intake_record) - if gate["status"] != "ready": - _print(gate) - return 2 - else: - print( - "warning: no --intake record; the task-performance intake " - "gate was not evaluated", file=sys.stderr, - ) - result = _optimization_session(args) - if gate is not None and Path(args.session).is_dir(): - result.update(attach_record(Path(args.session), gated_record, gate)) + result = start(args, _optimization_session) + if result.get("execution") == "not started": + _print(result) + return 2 if result.get("status") == "blocked" else 0 + else: + result = _optimization_session(args) _print(after_final(args, result)) if "exit_code" in result: return result["exit_code"] diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 1e364b11f..c77edf282 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -186,6 +186,8 @@ def _optimization_actions(stages, *, project=False): start.add_argument("--intake", type=Path, help="intake/v1 record; the campaign refuses to start until it is " "complete for the performance task") + start.add_argument("--prepare-intake", action="store_true", + help="Present the executable plan for approval without starting") start.add_argument("--repo", type=Path, required=True) start.add_argument("--include", action="append", required=True, help="Project-relative input file/directory; repeat for dependencies") diff --git a/src/inferrsi/apps/cli/campaign_intake.py b/src/inferrsi/apps/cli/campaign_intake.py new file mode 100644 index 000000000..097303597 --- /dev/null +++ b/src/inferrsi/apps/cli/campaign_intake.py @@ -0,0 +1,179 @@ +"""Bind the user's final brief to the same frozen inputs used by campaign start.""" + +import copy +import shlex +import shutil +import tempfile +from pathlib import Path + +from ...harness import candidates, optimization, project_service +from ..storage.artifacts import file_lock +from . import task_intake + + +def _blocked(reason, **details): + return {"status": "blocked", "execution": "not started", "reason": reason, **details} + + +def _execution(plan, args, staged): + # Retain the settings actually produced by Harness (including defaulted options). + # Implementation version fingerprints do not describe the user's execution choices. + launch = { + key: value + for key, value in plan.items() + if key not in ("runtime_identity", "runtime_version") + } + launch.update( + protocol=str(args.protocol.resolve()), instructions=str(args.instructions.resolve()) + ) + settings = plan["evaluation_settings"] + fields = { + "optimization.repository": plan["working_candidate"], + "protocol.comparison": args.evaluation_mode, + "environment.max_minutes": plan["max_seconds"] / 60, + "environment.rounds": plan["round_limit"], + "protocol.quality_failure_policy": "revert_candidate", + } + if args.evaluation_mode == "service_reuse": + primary = next(obj for obj in settings["objectives"] if obj["id"] == settings["ranking"][0]) + quality = settings["quality"] + comparison = "at_least" if quality["direction"] == "maximize" else "at_most" + relative = quality["mode"] == "baseline_comparison" + fields.update( + { + "acceptance.baseline_revision": plan["baseline_revision"], + "acceptance.metric_key": primary["key"], + "acceptance.metric_unit": primary["unit"], + "acceptance.direction": primary["direction"], + "protocol.quality_metric": quality["key"], + "protocol.quality_benchmark": quality["dataset"], + "protocol.quality_comparator": "at_most" if relative else comparison, + "protocol.quality_limit": quality["tolerance" if relative else "threshold"], + "protocol.timing_boundary": settings["conditions"]["timing_scope"], + "optimization.workload": settings["conditions"]["workload"], + "optimization.model": settings["conditions"]["model"], + "environment.repetitions": settings["sampling"]["baseline"]["repetitions"], + } + ) + if primary["threshold_type"] == "relative_percent": + fields["acceptance.min_improvement_pct"] = primary["gain_threshold"] + measure, quality_command = settings["commands"]["measure"], settings["commands"]["quality"] + else: + baseline = candidates.identity(staged / plan["baseline_path"]) + launch["baseline_identity"] = baseline + fields.update( + { + "acceptance.baseline_revision": baseline, + "acceptance.metric_key": settings["metric_key"], + "acceptance.metric_unit": settings["metric_unit"], + "acceptance.direction": settings["direction"], + "acceptance.min_improvement_pct": settings["min_improvement_pct"], + "protocol.timing_boundary": settings["scope"], + "environment.repetitions": settings["repetitions"], + } + ) + measure, quality_command = settings["measure_command"], settings["quality_command"] + fields.update( + { + "environment.baseline_command": measure, + "environment.candidate_command": measure, + "environment.quality_command": quality_command, + } + ) + return launch, fields + + +def _conflicts(conditions, expected, args): + conflicts = [] + for key, actual in expected.items(): + approved = conditions[key] + if key == "optimization.repository": + approved = str(Path(approved).expanduser().resolve()) + elif key.endswith("_command"): + approved = shlex.split(approved) + elif ( + key == "acceptance.baseline_revision" + and args.evaluation_mode == "abba" + and approved != actual + and (args.repo / ".git").exists() + ): + # A Git pin also requires that the retained inputs belong to that commit. + if actual == candidates.identity(args.repo, args.include): + actual = project_service.revision(args.repo, args.include) + if approved != actual: + conflicts.append({"field": key, "approved": approved, "actual": actual}) + return conflicts + + +def start(args, run_session): + if args.intake is None: + return _blocked( + "missing_intake", message="Supply --intake with an approved performance brief." + ) + path = args.intake.resolve() + if not path.is_file(): + return _blocked("missing_intake", message="Collect task intake before campaign start.") + destination = args.session.resolve() + if destination.exists() or any( + destination.is_relative_to(p.resolve()) for p in (args.repo, args.protocol) + ): + raise ValueError("Use a new campaign directory outside project/protocol") + try: + with file_lock(path.with_name(path.name + ".lock")): + gate, record = task_intake.campaign_gate(path) + if not gate["task_brief"] or (not args.prepare_intake and not gate["complete"]): + return gate + if not args.prepare_intake and "campaign_launch" not in record: + return _blocked( + "unbound_brief", message="Use --prepare-intake and review the executable brief." + ) + with tempfile.TemporaryDirectory(prefix="inferrsi-intake-") as tmp: + staged_args = copy.copy(args) + staged_args.session = Path(tmp) / "campaign" + frozen = run_session(staged_args, initialize=lambda _, plan: {"plan": plan}) + plan = frozen["plan"] + launch, expected = _execution(plan, args, staged_args.session) + brief = gate["task_brief"] + conflicts = _conflicts(brief["conditions"], expected, args) + if conflicts: + return _blocked("launch_conflict", conflicts=conflicts) + if args.prepare_intake: + return task_intake.prepare_launch(path, record, launch) + if launch != brief["campaign_launch"]: + return _blocked("launch_changed", + message="Prepare and review the changed launch.") + result = _initialize(staged_args.session, destination, plan, record, gate) + return {**result, "instructions": frozen["instructions"]} + except BlockingIOError: + return _blocked("record_busy", message="Retry when the intake update finishes.") + + +def _initialize(staged, destination, plan, record, gate): + conditions = gate["task_brief"]["conditions"] + plan["performance_target"] = { + name: conditions["protocol." + name] for name in ("target_kind", "target_value") + } + if plan.get("evaluation_mode") == "service_reuse": + settings = plan["evaluation_settings"] + primary = next(obj for obj in settings["objectives"] if obj["id"] == settings["ranking"][0]) + if primary["threshold_type"] != "relative_percent": + # A native absolute/point gain cannot stand in for the reviewed percentage gate. + plan["candidate_min_improvement_pct"] = conditions["acceptance.min_improvement_pct"] + else: + plan["evaluation_settings"]["quality_bound"] = { + name: conditions["protocol.quality_" + name] + for name in ("metric", "comparator", "limit") + } + receipt = task_intake.attach_record(staged, record, gate)["intake"] + relative = "plan/intake-" + receipt["sha256"] + ".json" + task_intake.write_record(staged / relative, receipt) + plan["intake_receipt"] = relative + destination.mkdir(parents=True, exist_ok=False) + try: + for path in staged.iterdir(): + shutil.move(str(path), destination / path.name) + result = optimization.initialize(destination, plan) + except BaseException: + shutil.rmtree(destination) + raise + return {**result, "intake": receipt} diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index d35115003..b19c72576 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -518,6 +518,8 @@ def _performance_brief(record: dict, spec: dict) -> dict: brief = {"record_id": record["record_id"], "revision": record["revision"], "task": record["task"], "performance_target": performance, "quality_gate": quality, "benchmark": values["protocol.quality_benchmark"], "conditions": values} + if "campaign_launch" in record: + brief["campaign_launch"] = record["campaign_launch"] brief["id"] = _BRIEF_QUESTION + hashlib.sha256(_canonical(brief).encode()).hexdigest() return brief diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index d677a852e..7643874a4 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -244,6 +244,16 @@ def campaign_gate(path: Path, *, expected_task: str = "task-performance", }, record +def prepare_launch(path, record, launch): + if record.get("campaign_launch") != launch: + record["campaign_launch"] = launch + record.pop("brief_decision", None) + record["revision"] += 1 + view = _evaluate_and_save(path, record, load_spec(record["task"]), None, + selecting_reference=False) + return {**view, "status": "prepared", "execution": "not started"} + + def attach_record(session_dir: Path, record: dict, gate: dict) -> dict: """Retain the gated record in the campaign directory and name its digest.""" digest = write_record(Path(session_dir) / "intake.json", record) @@ -252,6 +262,7 @@ def attach_record(session_dir: Path, record: dict, gate: dict) -> dict: "task": record["task"], "revision": record["revision"], "sha256": digest, + "brief_id": gate["task_brief"]["id"], "gate": gate["status"], }} @@ -263,7 +274,9 @@ def _render_brief(view: dict) -> list[str]: return [f"Task brief (revision {brief['revision']}, {view['brief_review']})", f"Performance target: {brief['performance_target']}", f"Accuracy on {brief['benchmark']}: {brief['quality_gate']}", - *(f" {key}: {value}" for key, value in brief["conditions"].items())] + *(f" {key}: {value}" for key, value in brief["conditions"].items()), + *([json.dumps(brief["campaign_launch"], ensure_ascii=False, indent=2)] + if "campaign_launch" in brief else [])] def _render_questions(view: dict) -> list[str]: diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 8a522793a..3ef1e569f 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -58,7 +58,9 @@ def _session_assess(root, directory, plan, execution, mechanism=None): if plan["task_source"] == "project": from inferrsi.harness.project import assess - return assess(directory, plan["evaluation_settings"], execution, mechanism=mechanism) + target = plan.get("performance_target") if directory.parent == root / "final" else None + return assess(directory, plan["evaluation_settings"], execution, mechanism=mechanism, + final_target=target) return run_protocol(root / "frozen", plan["frozen_files"]["optimization.py"], "assess", launch_directory=directory, directory=directory, settings=plan["evaluation_settings"], @@ -133,7 +135,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None knowledge_reader=None, retain_context=None, external_knowledge=None, external_provider=None, external_project=None, external_provider_for=None, - report_metadata=None) -> dict: + report_metadata=None, initialize=None) -> dict: """Run one operation; discovery and knowledge access are supplied by the caller.""" from inferrsi.harness import optimization @@ -141,6 +143,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if args.session_action == "start": import math + initialize = initialize or optimization.initialize + from inferrsi.harness.artifact_primitives import sha256 from inferrsi.harness.candidates import identity, retain from inferrsi.harness.task_protocol import prepare @@ -205,7 +209,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None "python": args.python, **settings, } - result = optimization.initialize(root, plan) + result = initialize(root, plan) result["instructions"] = ( "Run campaign baseline before candidate search. Record the measured " "bottleneck with campaign diagnose before knowledge or rounds. " @@ -272,7 +276,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None plan["external_knowledge_project"] = external_project if report_metadata is not None: plan["report_metadata"] = report_metadata - result = optimization.initialize(root, plan) + result = initialize(root, plan) operation = "campaign" if args.project_task else "benchmarks session" result["instructions"] = ( f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " diff --git a/src/inferrsi/harness/project.py b/src/inferrsi/harness/project.py index da27f389f..f1622844d 100644 --- a/src/inferrsi/harness/project.py +++ b/src/inferrsi/harness/project.py @@ -97,6 +97,20 @@ def _value(document, key): return value +def meets_target(target, *, baseline, candidate, direction): + if candidate is None: + return None + if target["target_kind"] == "absolute": + limit = target["target_value"] + return candidate <= limit if direction == "minimize" else candidate >= limit + if baseline in (None, 0): + return None + change = (candidate - baseline) / abs(baseline) * 100 + if not math.isfinite(change): + return None + return (change if direction == "maximize" else -change) >= target["target_value"] + + def inspect_step(directory: Path, settings: dict, definition: dict, execution: dict) -> dict: """Interpret one frozen script's explicit result, never guess a crash's cause.""" failure = {"status": "infrastructure_failure", "reason": "failed_execution"} @@ -115,6 +129,17 @@ def inspect_step(directory: Path, settings: dict, definition: dict, execution: d evidence = {relative: sha256(path)} rejected = document.get("status") == "candidate_failure" quality = _value(document, settings["quality_key"]) + bound = settings.get("quality_bound") + if definition["phase"] == "quality" and bound and quality is True: + score = _value(document, bound["metric"]) + if type(score) is bool and bound["metric"] == settings["quality_key"]: + score = int(score) + if type(score) not in (float, int) or not math.isfinite(score): + return {**failure, "reason": "missing_numeric_quality_evidence", + "evidence_files": evidence} + limit = bound["limit"] + quality = {"at_least": score >= limit, "at_most": score <= limit, "equal": score == limit}[ + bound["comparator"]] if rejected or (definition["phase"] == "quality" and quality is False): return {"status": ("candidate_failure" if definition["side"] == "candidate" else "infrastructure_failure"), @@ -137,7 +162,7 @@ def inspect_step(directory: Path, settings: dict, definition: dict, execution: d def assess(directory: Path, settings: dict, execution: dict, *, - mechanism: dict | None = None) -> dict: + mechanism: dict | None = None, final_target: dict | None = None) -> dict: """Judge one attempt; ``mechanism`` is the declaration bound before execution.""" evidence = {} @@ -229,6 +254,13 @@ def result(status, reason, **fields): verdict, reason = "FAIL", "explanation_" + explanation["status"] elif explanation["status"] != "explained": verdict, reason = "INCONCLUSIVE", "explanation_" + explanation["status"] + if final_target and verdict == "PASS": + passed = meets_target(final_target, baseline=before, candidate=after, + direction=settings["direction"]) + if passed is None: + verdict, reason = "INCONCLUSIVE", "final_target_evidence_unavailable" + elif not passed: + verdict, reason = "FAIL", "final_performance_target_not_met" accepted = verdict == "PASS" point = {"improvement_pct": improvement, "speedup": speedup} score, baseline_score, basis = after, before, "candidate_median" @@ -259,6 +291,7 @@ def result(status, reason, **fields): paired_statistics=paired, decision=decision, require_explanation=settings.get("require_explanation", False), profile_evidence=observed, explanation=explanation, - quality_contract="Only the supplied frozen quality script and its boolean result", + quality_contract=settings.get( + "quality_bound", "Only the supplied frozen quality script and its boolean result"), environment_qualification="Caller-managed; no automatic hardware isolation claim", ) diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index c1bcde2d3..1b7a7b564 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -858,12 +858,31 @@ def evaluate(role): if parent is not None else {"passed": True, "metrics": {}} ) + target = None + if role == "candidate" and "candidate_min_improvement_pct" in plan: + target = {"target_kind": "relative_improvement_pct", + "target_value": plan["candidate_min_improvement_pct"]} + elif role == "final": + target = plan.get("performance_target") + if target and gate["passed"]: + from .project import meets_target + + name = settings["ranking"][0] + objective = next(obj for obj in settings["objectives"] if obj["id"] == name) + gate["passed"] = meets_target( + target, baseline=initial["measurements"]["values"][name], + candidate=measured["values"][name], direction=objective["direction"]) + if gate["passed"] is None: + raise ValueError("Undefined relative performance target against the baseline") + if not gate["passed"]: + gate["reason"] = ("final_performance_target_not_met" if role == "final" + else "performance_gate_not_met") if not gate["passed"]: skipped(("quality",), "performance_gate_not_met") if role != "candidate": skipped(("profile",), "not_required") record["assessment"] = assessment( - "FAIL", "performance_gate_not_met", performance=gate + "FAIL", gate["reason"], performance=gate ) elif pending.get("reference_kind") == "parent": skipped(("quality", "profile"), "performance_reference_only") diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index bb6b7d531..3e2192c56 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "e4cab3fc2abdbeb5f7faead828efe8a398b72fa1", + "source_revision": "6f5775d29d3546732113900ef811d60a5943aa62", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index e5825d056..4fc6071a2 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -1205,7 +1205,7 @@ "description": "Use when a correct inference baseline misses a latency, throughput, memory or cost target. Compare compatible changes under the user's workload and quality gate." }, "files": { - "SKILL.md": "cf90e10f1cc101efa4fd4aa5689bf78992a86466354809ada078b2363837ea20", + "SKILL.md": "46b44df9d2b6b91ae305df21536d9cf04903b3ea442b0413b3f2319452faafb9", "intake.json": "13ecae20885d7ea07bbb00b84be3481f4a825590e2e4044abd6cdb2d6bcaf680" } }, diff --git a/tests/apps/test_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py index b1eadd835..bd7db6544 100644 --- a/tests/apps/test_engineering_benchmark_plugins.py +++ b/tests/apps/test_engineering_benchmark_plugins.py @@ -5,6 +5,7 @@ from tests.apps.test_codex_plugin import distribution as distribution from tests.apps.test_codex_plugin import invoke from tests.apps.test_project_optimization import project as project +from tests.fixtures.campaign_intake import approved_start from tests.fixtures.diagnosis import diagnosis_args @@ -67,7 +68,7 @@ def test_current_agent_session_uses_bundled_task_and_enforces_rounds(distributio def test_isolated_plugin_runs_project_round_and_retained_final(distribution, tmp_path, project): repo, protocol, instructions, root = project started = invoke( - distribution, tmp_path, "campaign", "start", "--directory", str(root), + distribution, tmp_path, *approved_start(["campaign", "start", "--directory", str(root), "--repo", str(repo), "--include", "engine.py", "--include", "config.json", "--protocol", str(protocol), "--instructions", str(instructions), "--measure-command", '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', @@ -76,6 +77,7 @@ def test_isolated_plugin_runs_project_round_and_retained_final(distribution, tmp "--quality-key", "correct", "--scope", "synthetic-software-control", "--min-improvement-pct", "1", "--warmups", "0", "--repetitions", "1", "--rounds", "1", "--max-minutes", "5", "--evaluation-timeout-seconds", "30", + "--python", "python3"]), ) assert started.returncode == 0, started.stderr diagnosed = invoke(distribution, tmp_path, *diagnosis_args(root, "campaign")) diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index d3a46329c..a556aaea1 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -11,6 +11,7 @@ from inferrsi.apps.views.optimization_chart import render_result from inferrsi.harness.artifact_primitives import digest from inferrsi.harness.optimization import read_records +from tests.fixtures.campaign_intake import approved_start from tests.fixtures.diagnosis import diagnosis_args # Device-wide factor applied to every timed value of one measurement call, cycling per @@ -56,7 +57,7 @@ def project(tmp_path): def start(project, capsys, *extra, repetitions=8): repo, protocol, instructions, root = project - code = main([ + code = main(approved_start([ "campaign", "start", "--directory", str(root), "--repo", str(repo), "--include", "engine.py", "--include", "config.json", "--protocol", str(protocol), "--instructions", str(instructions), "--measure-command", @@ -67,7 +68,7 @@ def start(project, capsys, *extra, repetitions=8): "--repetitions", str(repetitions), "--warmups", "1", "--min-improvement-pct", "1", "--rounds", "4", "--round-mode", "up_to", "--max-minutes", "5", "--evaluation-timeout-seconds", "20", *extra, - ]) + ])) if code == 0: # Rounds require a retained bottleneck diagnosis (#519). assert main(diagnosis_args(root, "campaign")) == 0 capsys.readouterr() diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index f4f2887d9..27defac60 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -12,6 +12,7 @@ from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.harness import optimization_session from inferrsi.harness.optimization import read_records +from tests.fixtures.campaign_intake import approved_start, preparation_arguments from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -59,7 +60,8 @@ def start_arguments(project, *, direction="maximize", mode="up_to", extra=()): def start(project, capsys, *, direction="maximize", mode="up_to", extra=()): - assert main(start_arguments(project, direction=direction, mode=mode, extra=extra)) == 0 + args = start_arguments(project, direction=direction, mode=mode, extra=extra) + assert main(approved_start(args)) == 0 result = json.loads(capsys.readouterr().out) assert result["working_candidate"] == str(project[0]) assert result["next_action"] == "record_bottleneck_diagnosis" @@ -169,7 +171,7 @@ def find_spec(self, fullname, path=None, target=None): ] result = subprocess.run( [sys.executable, "-X", "utf8", "-c", script], - input=json.dumps({"start": start_arguments(project), "commands": commands, + input=json.dumps({"start": approved_start(start_arguments(project)), "commands": commands, "repo": str(repo), "root": str(root)}), capture_output=True, text=True, encoding="utf-8", timeout=60, ) @@ -427,7 +429,7 @@ def test_project_knowledge_off_and_manual_record_writes_are_rejected(project, ca def test_declared_paths_cannot_escape_project(project, capsys): with pytest.raises(SystemExit): - start(project, capsys, extra=("--include", "../protocol")) + main(preparation_arguments(start_arguments(project, extra=("--include", "../protocol")))) assert not project[3].exists() diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 1c99f94fe..eae4c2096 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -14,6 +14,7 @@ from inferrsi.apps.cli.arguments import parser from inferrsi.apps.delivery import project, read_bundle from inferrsi.harness import optimization, project_service +from tests.fixtures.campaign_intake import preparation_arguments from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings, submit from tests.fixtures.service_reuse import campaign as campaign from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints @@ -1500,7 +1501,7 @@ def test_standalone_capture_leaves_search_budget_and_reserve_intact(campaign, mo def test_paired_and_explanation_switches_are_refused_in_service_mode(campaign, switch): # Both switches read AB/BA pairs and profiles; service reuse must not silently drop them. with pytest.raises(SystemExit): - main([*campaign["start"], *switch]) + main(preparation_arguments([*campaign["start"], *switch])) campaign["capsys"].readouterr() assert not (campaign["root"] / "plan.json").exists() @@ -1518,3 +1519,27 @@ def test_mechanism_declaration_is_refused_in_service_mode(campaign, tmp_path): campaign["capsys"].readouterr() state = json.loads((campaign["root"] / "state.json").read_text()) assert state["pending"] is None and not state.get("attempts", [])[1:] + + +def test_service_start_compares_approved_gates_and_full_configuration(campaign): + from tests.fixtures.campaign_intake import approved_start + + args = approved_start(campaign["start"]) + original = json.loads(campaign["config"].read_bytes()) + changed = settings() + changed["quality"]["threshold"] = 0 + campaign["config"].write_text(json.dumps(changed)) + assert main(args) == 2 + blocked = json.loads(campaign["capsys"].readouterr().out) + assert blocked["reason"] == "launch_conflict" + assert blocked["conflicts"][0]["field"] == "protocol.quality_limit" + changed = settings() + changed["sampling"]["final"]["warmups"] += 1 + campaign["config"].write_text(json.dumps(changed)) + assert main(args) == 2 + assert json.loads(campaign["capsys"].readouterr().out)["reason"] == "launch_changed" + assert not campaign["root"].exists() + campaign["config"].write_text(json.dumps(original)) + assert main(args) == 0 + plan = project_service.read(campaign["root"] / "plan.json") + assert (campaign["root"] / plan["intake_receipt"]).is_file() diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index 88221e8e4..6b8d45924 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -12,6 +12,7 @@ from inferrsi.apps.cli import intake_contract as intake from inferrsi.apps.cli import task_intake from tests.apps.test_project_optimization import project, start_arguments # noqa: F401 +from tests.fixtures.campaign_intake import approved_start FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "intake" PERFORMANCE = FIXTURES / "performance" @@ -368,23 +369,24 @@ def test_campaign_start_refuses_an_incomplete_record_before_writing(project, tmp def test_campaign_start_retains_the_record_it_gated(project, tmp_path, capsys): # noqa: F811 - record = tmp_path / "record.json" - record.write_text(json.dumps(approved_record()), encoding="utf-8") - assert cli.main(start_arguments(project, extra=("--intake", str(record)))) == 0 + args = approved_start(start_arguments(project)) + record = Path(args[-1]) + assert cli.main(args) == 0 result = json.loads(capsys.readouterr().out) retained = project[3] / "intake.json" assert result["intake"]["gate"] == "ready" assert result["intake"]["sha256"] == hashlib.sha256(retained.read_bytes()).hexdigest() - assert json.loads(retained.read_text(encoding="utf-8")) == approved_record() + assert json.loads(retained.read_bytes()) == json.loads(record.read_bytes()) + plan = json.loads((project[3] / "plan.json").read_bytes()) + assert json.loads((project[3] / plan["intake_receipt"]).read_bytes()) == result["intake"] # The retained record does not disturb the managed campaign's own records. assert cli.main(["campaign", "status", "--directory", str(project[3])]) == 0 -def test_campaign_start_without_a_record_warns_and_proceeds(project, capsys): # noqa: F811 - assert cli.main(start_arguments(project)) == 0 - captured = capsys.readouterr() - assert "intake gate was not evaluated" in captured.err - assert "intake" not in json.loads(captured.out) +def test_campaign_start_without_a_record_is_blocked(project, capsys): # noqa: F811 + assert cli.main(start_arguments(project)) == 2 + assert json.loads(capsys.readouterr().out)["reason"] == "missing_intake" + assert not project[3].exists() def test_day0_blocks_only_device_execution(): @@ -703,3 +705,86 @@ def test_loaded_approved_record_reopens_unusable_execution_values(project, tmp_p view = json.loads(capsys.readouterr().out) assert view["brief_review"] == "awaiting_confirmation" assert not view["complete"] + + +@pytest.mark.parametrize(("flag", "value", "reason"), [ + ("--metric-unit", "other", "launch_conflict"), + ("--measure-command", "{python} {protocol}/different.py {result}", "launch_conflict"), + ("--rounds", "2", "launch_conflict"), + ("--quality-key", "different", "launch_changed"), + ("--warmups", "7", "launch_changed"), +]) +def test_changed_launch_never_creates_campaign(project, capsys, flag, value, reason): # noqa: F811 + args = approved_start(start_arguments(project)) + assert cli.main([*args, flag, value]) == 2 + assert json.loads(capsys.readouterr().out)["reason"] == reason + assert not project[3].exists() + + +def test_preparation_invalidates_only_changed_brief(project, capsys): # noqa: F811 + args = approved_start(start_arguments(project)) + record = Path(args[-1]) + approved = json.loads(record.read_bytes())["brief_decision"] + assert cli.main([*args, "--prepare-intake"]) == 0 + unchanged = json.loads(capsys.readouterr().out) + assert unchanged["brief_review"] == "approved" + assert json.loads(record.read_bytes())["brief_decision"] == approved + assert cli.main([*args, "--warmups", "2", "--prepare-intake"]) == 0 + revised = json.loads(capsys.readouterr().out) + assert revised["brief_review"] == "awaiting_confirmation" + assert revised["task_brief"]["id"] != unchanged["task_brief"]["id"] + assert cli.main([*args, "--warmups", "2"]) == 2 + assert not project[3].exists() + + +def test_planning_only_and_changed_protocol_are_refused(project, capsys): # noqa: F811 + args = start_arguments(project) + path = project[3].with_suffix(".intake.json") + task_intake.write_record(path, approved_record()) + assert cli.main([*args, "--intake", str(path)]) == 2 + assert json.loads(capsys.readouterr().out)["reason"] == "unbound_brief" + approved = approved_start(args) + script = project[1] / "quality.py" + script.write_text(script.read_text() + "\n# Updated validator\n") + assert cli.main(approved) == 2 + assert json.loads(capsys.readouterr().out)["reason"] == "launch_changed" + assert not project[3].exists() + + +@pytest.mark.parametrize(("kind", "goal"), [("absolute", 30), ("relative_improvement_pct", 200)]) +def test_independent_final_checks_approved_target(project, capsys, kind, goal): # noqa: F811 + from tests.apps.test_project_optimization import submit + from tests.fixtures.diagnosis import diagnosis_args + + args = approved_start(start_arguments(project), overrides={ + "protocol.target_kind": kind, "protocol.target_value": goal}) + assert cli.main(args) == 0 + capsys.readouterr() + assert cli.main(diagnosis_args(project[3], "campaign")) == 0 + capsys.readouterr() + code, view = submit(project, capsys, 20) + assert code == 0 and view["best"]["score"] == 20 + cli.main(["campaign", "final", "--directory", str(project[3]), "--reason", "retest"]) + capsys.readouterr() + final = json.loads((project[3] / "state.json").read_bytes())["final"]["assessment"] + assert (final["verdict"], final["reason"]) == ("FAIL", "final_performance_target_not_met") + + +def test_boolean_quality_success_does_not_override_numeric_limit(project, capsys): # noqa: F811 + from tests.apps.test_project_optimization import submit + from tests.fixtures.diagnosis import diagnosis_args + + (project[1] / "quality.py").write_text( + "import json, sys\nfrom pathlib import Path\n" + "value = json.loads((Path(sys.argv[1])/'config.json').read_text())['metric']\n" + "Path(sys.argv[2]).write_text(json.dumps({'correct':True,'errors':value-10}))\n") + args = approved_start(start_arguments(project), overrides={ + "protocol.quality_metric": "errors", "protocol.quality_limit": 0, + "protocol.quality_comparator": "at_most", "protocol.quality_unit": "tokens"}) + assert cli.main(args) == 0 + capsys.readouterr() + assert cli.main(diagnosis_args(project[3], "campaign")) == 0 + capsys.readouterr() + _, view = submit(project, capsys, 20) + assert view["best"]["kind"] == "baseline" + assert view["latest_observation"]["assessment"]["quality_passed"] is False diff --git a/tests/fixtures/campaign_intake.py b/tests/fixtures/campaign_intake.py new file mode 100644 index 000000000..8260550e8 --- /dev/null +++ b/tests/fixtures/campaign_intake.py @@ -0,0 +1,126 @@ +"""Synthetic user approval for integration tests that exercise measured campaigns.""" + +import io +import json +import shlex +from contextlib import redirect_stdout +from pathlib import Path + +from inferrsi.apps.cli import intake_contract as intake +from inferrsi.apps.cli import main, task_intake +from inferrsi.apps.cli.arguments import parser +from inferrsi.harness import candidates, project_service + + +def approved_start(arguments, *, overrides=None): + args = parser().parse_args(arguments) + path = args.session.with_suffix(".intake.json") + fixture = Path(__file__).parent / "intake/performance/complete.json" + data = json.loads(fixture.read_text()) + values = {**data["fields"]["values"], **data["acceptance"]["values"]} + values.update( + { + "optimization.repository": str(args.repo.resolve()), + "environment.rounds": args.rounds, + "environment.max_minutes": args.max_minutes, + "protocol.comparison": args.evaluation_mode, + "protocol.target_kind": "absolute", + } + ) + if args.evaluation_mode == "service_reuse": + cfg = project_service.read(args.evaluation_config) + project_service.validate(cfg) + obj = next(o for o in cfg["objectives"] if o["id"] == cfg["ranking"][0]) + q = cfg["quality"] + cmp = "at_least" if q["direction"] == "maximize" else "at_most" + relative = q["mode"] == "baseline_comparison" + values.update( + { + "acceptance.baseline_revision": project_service.revision(args.repo, args.include), + "acceptance.metric_key": obj["key"], + "acceptance.metric_unit": obj["unit"], + "acceptance.direction": obj["direction"], + "acceptance.min_improvement_pct": obj["gain_threshold"], + "protocol.target_value": obj["domain"]["max"] + if obj["direction"] == "minimize" + else obj["domain"]["min"], + "protocol.quality_benchmark": q["dataset"], + "protocol.quality_metric": q["key"], + "protocol.quality_comparator": "at_most" if relative else cmp, + "protocol.quality_limit": q["tolerance" if relative else "threshold"], + "protocol.service_lifecycle": "fixture owned process", + "optimization.workload": cfg["conditions"]["workload"], + "optimization.model": cfg["conditions"]["model"], + "protocol.timing_boundary": cfg["conditions"]["timing_scope"], + "environment.repetitions": cfg["sampling"]["baseline"]["repetitions"], + "environment.baseline_command": shlex.join(cfg["commands"]["measure"]), + "environment.candidate_command": shlex.join(cfg["commands"]["measure"]), + "environment.quality_command": shlex.join(cfg["commands"]["quality"]), + } + ) + else: + values.update( + { + "acceptance.baseline_revision": candidates.identity(args.repo, args.include), + "acceptance.metric_key": args.metric_key, + "acceptance.metric_unit": args.metric_unit, + "acceptance.direction": args.direction, + "acceptance.min_improvement_pct": args.min_improvement_pct, + "protocol.target_value": 10000 if args.direction == "minimize" else 0, + "protocol.quality_metric": args.quality_key, + "protocol.quality_comparator": "equal", + "protocol.quality_limit": 1, + "protocol.quality_unit": "boolean", + "protocol.timing_boundary": args.scope, + "environment.repetitions": args.repetitions, + "environment.baseline_command": args.measure_command, + "environment.candidate_command": args.measure_command, + "environment.quality_command": args.quality_command, + } + ) + values.update(overrides or {}) + spec = task_intake.load_spec("task-performance") + record = intake.new_record("task-performance", record_id="fixture-user") + record = intake.set_fields(record, spec, values, source="prompt") + accepted = {key: value for key, value in values.items() if key.startswith("acceptance.")} + record = intake.set_fields(record, spec, accepted, source="issue") + task_intake.write_record(path, record) + invocation = [*arguments, "--intake", str(path)] + output = io.StringIO() + with redirect_stdout(output): + assert main([*invocation, "--prepare-intake"]) == 0, output.getvalue() + brief = json.loads(output.getvalue())["task_brief"] + assert ( + main( + [ + "task", + "intake", + "answer", + "--record", + str(path), + "--question", + brief["id"], + "--value", + "approve", + "--json", + ] + ) + == 0 + ) + return invocation + + +def preparation_arguments(arguments): + """Reach Harness validation with a complete planning brief even for invalid flags.""" + args = parser().parse_args(arguments) + path = args.session.with_suffix(".intake.json") + fixture = Path(__file__).parent / "intake/performance/complete.json" + data = json.loads(fixture.read_text()) + spec = task_intake.load_spec("task-performance") + record = intake.new_record("task-performance", record_id="fixture-user") + record = intake.set_fields(record, spec, data["fields"]["values"], source="prompt") + record = intake.set_fields(record, spec, {**data["acceptance"]["values"], + intake.REFERENCE: data["fields"]["values"][intake.REFERENCE]}, + source="issue") + task_intake.write_record(path, record) + return [*arguments, "--intake", str(path), "--prepare-intake"] diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index ae97d07ad..c2ea5b910 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -13,6 +13,7 @@ from inferrsi.harness import artifact_primitives from inferrsi.harness.records import evidence, knowledge_capture from inferrsi.knowledge import knowledge_operations +from tests.fixtures.campaign_intake import approved_start, preparation_arguments from tests.fixtures.diagnosis import diagnosis_args @@ -175,7 +176,7 @@ def campaign(tmp_path, capsys): def call(campaign, action, *extra, expected=0): args = ( - campaign["start"] + approved_start(campaign["start"]) if action == "start" else ["campaign", action, "--session", str(campaign["root"]), *map(str, extra)] ) @@ -208,5 +209,7 @@ def submit(campaign, *, expected=0, retry=None, **changes): def rejected(arguments): with pytest.raises(SystemExit) as raised: + if arguments[:2] == ["campaign", "start"]: + arguments = preparation_arguments(arguments) main(arguments) return raised.value.code From 694ec791f5dde3f1aeee888551157a5fabfa10f3 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:00:34 +0800 Subject: [PATCH 13/26] Show the service quality reference and tolerance on the approval card Use the direction of the retained baseline quality score when describing allowed degradation. Reopen decisions bound to the earlier wording and compare both directions and both modes with the service evaluator. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 3 ++ src/inferrsi/apps/cli/intake_contract.py | 30 ++++++++++- tests/apps/test_project_service_reuse.py | 63 ++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 1 deletion(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index e3e28471e..cbabc7e49 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -207,6 +207,9 @@ compared as 1 or 0. The independent final checks the approved absolute bound or relative improvement against the pinned baseline. For service reuse, the first ranked objective names the final metric and the configuration supplies its dataset, score key, threshold or allowed degradation, commands and sampling. +The bound brief displays an absolute score threshold or the allowed change from +the retained baseline for the current comparison epoch. Higher-is-better scores +may drop by the approved tolerance; lower-is-better scores may rise by it. ## Cards and text fallback diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index b19c72576..e7e667063 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -500,6 +500,24 @@ def _frozen_conflicts(record: dict, spec: dict, frozen: dict | None) -> list[dic return conflicts +def _service_quality_line(quality: dict, unit: str) -> str: + if (quality["mode"] not in ("absolute", "baseline_comparison") + or quality["direction"] not in ("maximize", "minimize")): + raise IntakeError("invalid_record", "Unknown service quality mode or direction") + metric = quality["key"] + higher = quality["direction"] == "maximize" + direction = "higher is better" if higher else "lower is better" + operator = ">=" if higher else "<=" + if quality["mode"] == "absolute": + limit = str(quality["threshold"]).removesuffix(".0") + return f"{metric} {operator} {limit} {unit} (absolute threshold; {direction})" + tolerance = str(quality["tolerance"]).removesuffix(".0") + sign = "-" if higher else "+" + return (f"{metric} {operator} baseline {metric} {sign} {tolerance} {unit} " + f"(baseline comparison; {direction}; reference: retained baseline score " + "for the current comparison epoch)") + + def _performance_brief(record: dict, spec: dict) -> dict: values = {field["path"]: _coerce(field, record["fields"][field["path"]]["value"]) for field in spec["fields"] if _applicable(record, field)} @@ -519,7 +537,17 @@ def _performance_brief(record: dict, spec: dict) -> dict: "task": record["task"], "performance_target": performance, "quality_gate": quality, "benchmark": values["protocol.quality_benchmark"], "conditions": values} if "campaign_launch" in record: - brief["campaign_launch"] = record["campaign_launch"] + launch = record["campaign_launch"] + if not isinstance(launch, dict): + raise IntakeError("invalid_record", "campaign_launch must be an object") + if launch.get("evaluation_mode") == "service_reuse": + try: + brief["quality_gate"] = _service_quality_line( + launch["evaluation_settings"]["quality"], values["protocol.quality_unit"]) + except (KeyError, TypeError) as exc: + raise IntakeError("invalid_record", + "Incomplete service quality conditions") from exc + brief["campaign_launch"] = launch brief["id"] = _BRIEF_QUESTION + hashlib.sha256(_canonical(brief).encode()).hexdigest() return brief diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index eae4c2096..83e65ae16 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1543,3 +1543,66 @@ def test_service_start_compares_approved_gates_and_full_configuration(campaign): assert main(args) == 0 plan = project_service.read(campaign["root"] / "plan.json") assert (campaign["root"] / plan["intake_receipt"]).is_file() + + +@pytest.mark.parametrize(("mode", "direction", "expected", "good", "bad"), [ + ("absolute", "maximize", "accuracy >= 90 points (absolute threshold; higher is better)", + 90, 89.95), + ("absolute", "minimize", "accuracy <= 90 points (absolute threshold; lower is better)", + 89.95, 90.05), + ("baseline_comparison", "maximize", + "accuracy >= baseline accuracy - 0.1 points (baseline comparison; higher is better; " + "reference: retained baseline score for the current comparison epoch)", 89.95, 89.8), + ("baseline_comparison", "minimize", + "accuracy <= baseline accuracy + 0.1 points (baseline comparison; lower is better; " + "reference: retained baseline score for the current comparison epoch)", 90.05, 90.2), +]) +def test_executable_service_brief_describes_the_actual_quality_gate( + campaign, mode, direction, expected, good, bad +): + from inferrsi.apps.cli import task_intake + from tests.fixtures.campaign_intake import approved_start + + config = settings() + quality = config["quality"] + quality.update(mode=mode, direction=direction, key="accuracy") + if mode == "absolute": + quality["threshold"] = 90 + else: + quality.pop("threshold") + quality["tolerance"] = 0.1 + campaign["config"].write_text(json.dumps(config)) + args = approved_start(campaign["start"], overrides={"protocol.quality_unit": "points"}) + gate, _ = task_intake.campaign_gate(Path(args[-1])) + assert gate["brief_review"] == "approved" + assert gate["task_brief"]["quality_gate"] == expected + assert expected in task_intake.render(gate) + assert project_service.quality_passed(config, good, reference=90) + assert not project_service.quality_passed(config, bad, reference=90) + + +def test_old_absolute_wording_cannot_approve_a_relative_service_gate(campaign): + import hashlib + + from inferrsi.apps.cli import task_intake + from tests.fixtures.campaign_intake import approved_start + + config = settings() + config["quality"].pop("threshold") + config["quality"].update(mode="baseline_comparison", tolerance=0.1) + campaign["config"].write_text(json.dumps(config)) + args = approved_start(campaign["start"], overrides={"protocol.quality_unit": "points"}) + path = Path(args[-1]) + gate, record = task_intake.campaign_gate(path) + old_brief = dict(gate["task_brief"]) + old_brief.pop("id") + old_brief["quality_gate"] = "quality <= 0.1 points" + payload = json.dumps(old_brief, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + old_id = "q:task_brief:" + hashlib.sha256(payload.encode()).hexdigest() + record["brief_decision"]["question"] = old_id + task_intake.write_record(path, record) + assert main(args) == 2 + reopened = json.loads(campaign["capsys"].readouterr().out) + assert reopened["brief_review"] == "awaiting_confirmation" + assert "baseline quality - 0.1 points" in reopened["task_brief"]["quality_gate"] + assert not campaign["root"].exists() From 0fb750231a94174fc26b092e5d526280dfbbb349 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:08:10 +0800 Subject: [PATCH 14/26] Express baseline-relative quality limits consistently throughout the brief Bind the comparator to the score direction, present the tolerance and reference in structured conditions and summaries, and reopen older contradictory approvals. Invalidate a prepared launch when its intake fields change. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 3 ++ src/inferrsi/apps/cli/campaign_intake.py | 7 ++- src/inferrsi/apps/cli/intake_contract.py | 62 ++++++++++++++++++------ src/inferrsi/apps/cli/task_intake.py | 1 + tests/apps/test_project_service_reuse.py | 47 ++++++++++++++++-- tests/fixtures/campaign_intake.py | 2 +- 6 files changed, 102 insertions(+), 20 deletions(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index cbabc7e49..f32516f79 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -210,6 +210,9 @@ dataset, score key, threshold or allowed degradation, commands and sampling. The bound brief displays an absolute score threshold or the allowed change from the retained baseline for the current comparison epoch. Higher-is-better scores may drop by the approved tolerance; lower-is-better scores may rise by it. +The comparator applies to the candidate score in both modes. For a relative +gate, the brief labels the numeric allowance as `protocol.quality_baseline_tolerance` +and identifies the retained score in `protocol.quality_reference`. ## Cards and text fallback diff --git a/src/inferrsi/apps/cli/campaign_intake.py b/src/inferrsi/apps/cli/campaign_intake.py index 097303597..b187effc8 100644 --- a/src/inferrsi/apps/cli/campaign_intake.py +++ b/src/inferrsi/apps/cli/campaign_intake.py @@ -47,7 +47,7 @@ def _execution(plan, args, staged): "acceptance.direction": primary["direction"], "protocol.quality_metric": quality["key"], "protocol.quality_benchmark": quality["dataset"], - "protocol.quality_comparator": "at_most" if relative else comparison, + "protocol.quality_comparator": comparison, "protocol.quality_limit": quality["tolerance" if relative else "threshold"], "protocol.timing_boundary": settings["conditions"]["timing_scope"], "optimization.workload": settings["conditions"]["workload"], @@ -86,7 +86,10 @@ def _execution(plan, args, staged): def _conflicts(conditions, expected, args): conflicts = [] for key, actual in expected.items(): - approved = conditions[key] + if key == "protocol.quality_limit" and "protocol.quality_baseline_tolerance" in conditions: + approved = conditions["protocol.quality_baseline_tolerance"] + else: + approved = conditions[key] if key == "optimization.repository": approved = str(Path(approved).expanduser().resolve()) elif key.endswith("_command"): diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index e7e667063..6aeec7bbd 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -317,6 +317,25 @@ def _bound_value(record: dict, path: str, entry: dict) -> bool: return entry["source"] == "issue" +def _bound_service_quality(record: dict) -> dict | None: + launch = record.get("campaign_launch", {}) + if not isinstance(launch, dict): + raise IntakeError("invalid_record", "campaign_launch must be an object") + if launch.get("evaluation_mode") != "service_reuse": + return None + try: + quality = launch["evaluation_settings"]["quality"] + if (quality["mode"] not in ("absolute", "baseline_comparison") + or quality["direction"] not in ("maximize", "minimize") + or not isinstance(quality["key"], str) + or not isinstance(quality.get("threshold" if quality["mode"] == "absolute" + else "tolerance"), (int, float))): + raise ValueError + except (TypeError, KeyError, ValueError) as exc: + raise IntakeError("invalid_record", "Invalid bound service quality conditions") from exc + return quality + + def reconcile_record(record: dict, spec: dict) -> dict: """Recheck provenance, including older records that trusted the source label alone.""" _check(record, spec) @@ -339,6 +358,18 @@ def reconcile_record(record: dict, spec: dict) -> dict: continue bound = _bound_value(record, path, entry) entry["status"] = _status_for(field, entry["source"], bound=bound) + quality = _bound_service_quality(updated) + comparator = _entry(updated, "protocol.quality_comparator") + if quality and quality["mode"] == "baseline_comparison" and comparator["status"] in SETTLED: + expected = "at_least" if quality["direction"] == "maximize" else "at_most" + if comparator["value"] != expected: + # Legacy maximize approvals used the comparator for the tolerance. + updated["fields"]["protocol.quality_comparator"] = { + "value": None, "source": comparator["source"], "status": "conflicting", + "candidates": [{"value": comparator["value"], "source": comparator["source"]}, + {"value": expected, "source": "service quality direction"}], + } + reopened = True if reopened: _bump(updated, updated["revision"] + 1) return updated @@ -346,6 +377,7 @@ def reconcile_record(record: dict, spec: dict) -> dict: def _bump(record: dict, next_revision: int) -> None: record.pop("brief_decision", None) + record.pop("campaign_launch", None) record["revision"] = next_revision @@ -501,9 +533,6 @@ def _frozen_conflicts(record: dict, spec: dict, frozen: dict | None) -> list[dic def _service_quality_line(quality: dict, unit: str) -> str: - if (quality["mode"] not in ("absolute", "baseline_comparison") - or quality["direction"] not in ("maximize", "minimize")): - raise IntakeError("invalid_record", "Unknown service quality mode or direction") metric = quality["key"] higher = quality["direction"] == "maximize" direction = "higher is better" if higher else "lower is better" @@ -537,17 +566,17 @@ def _performance_brief(record: dict, spec: dict) -> dict: "task": record["task"], "performance_target": performance, "quality_gate": quality, "benchmark": values["protocol.quality_benchmark"], "conditions": values} if "campaign_launch" in record: - launch = record["campaign_launch"] - if not isinstance(launch, dict): - raise IntakeError("invalid_record", "campaign_launch must be an object") - if launch.get("evaluation_mode") == "service_reuse": - try: - brief["quality_gate"] = _service_quality_line( - launch["evaluation_settings"]["quality"], values["protocol.quality_unit"]) - except (KeyError, TypeError) as exc: - raise IntakeError("invalid_record", - "Incomplete service quality conditions") from exc - brief["campaign_launch"] = launch + brief["campaign_launch"] = record["campaign_launch"] + service_quality = _bound_service_quality(record) + if service_quality: + brief["quality_gate"] = _service_quality_line( + service_quality, values["protocol.quality_unit"]) + values["protocol.quality_mode"] = service_quality["mode"] + values["protocol.quality_direction"] = service_quality["direction"] + if service_quality["mode"] == "baseline_comparison": + values["protocol.quality_baseline_tolerance"] = values.pop("protocol.quality_limit") + values["protocol.quality_reference"] = ( + "retained baseline score for the current comparison epoch") brief["id"] = _BRIEF_QUESTION + hashlib.sha256(_canonical(brief).encode()).hexdigest() return brief @@ -761,6 +790,11 @@ def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: proposed[path] = entry.get("value") elif status in ("unknown", "conflicting", "stale", "superseded"): unknown.append(path) + conditions = (view["task_brief"] or {}).get("conditions", {}) + if "protocol.quality_baseline_tolerance" in conditions: + for values in (confirmed, proposed): + if "protocol.quality_limit" in values: + values["protocol.quality_baseline_tolerance"] = values.pop("protocol.quality_limit") return { "schema_version": SCHEMA_VERSION, "task": spec["task"], diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 7643874a4..88988dcf3 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -143,6 +143,7 @@ def _evaluate_gate(record: dict, spec: dict, frozen_path: Path | None, record.pop("selected_gate", None) record.pop("selected_gate_file", None) record.pop("brief_decision", None) + record.pop("campaign_launch", None) record["fields"][intake.REFERENCE] = { "value": reference, "source": "repo_inspection", "status": "assumed", } diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 83e65ae16..67963ff0e 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1576,7 +1576,24 @@ def test_executable_service_brief_describes_the_actual_quality_gate( gate, _ = task_intake.campaign_gate(Path(args[-1])) assert gate["brief_review"] == "approved" assert gate["task_brief"]["quality_gate"] == expected - assert expected in task_intake.render(gate) + rendered = task_intake.render(gate) + assert expected in rendered + comparator = "at_least" if direction == "maximize" else "at_most" + assert f"protocol.quality_comparator: {comparator}" in rendered + assert f"protocol.quality_direction: {direction}" in rendered + if mode == "baseline_comparison": + assert "protocol.quality_baseline_tolerance: 0.1" in rendered + assert "protocol.quality_reference: retained baseline score" in rendered + assert "protocol.quality_limit:" not in rendered + assert "protocol.quality_limit" not in gate["task_brief"]["conditions"] + from inferrsi.apps.cli import intake_contract + + summary = intake_contract.summary(task_intake.read_record(Path(args[-1])), + task_intake.load_spec("task-performance")) + assert "protocol.quality_limit" not in task_intake.render_summary(summary) + else: + assert "protocol.quality_limit: 90" in rendered + assert "protocol.quality_baseline_tolerance" not in rendered assert project_service.quality_passed(config, good, reference=90) assert not project_service.quality_passed(config, bad, reference=90) @@ -1589,7 +1606,7 @@ def test_old_absolute_wording_cannot_approve_a_relative_service_gate(campaign): config = settings() config["quality"].pop("threshold") - config["quality"].update(mode="baseline_comparison", tolerance=0.1) + config["quality"].update(mode="baseline_comparison", direction="minimize", tolerance=0.1) campaign["config"].write_text(json.dumps(config)) args = approved_start(campaign["start"], overrides={"protocol.quality_unit": "points"}) path = Path(args[-1]) @@ -1597,6 +1614,10 @@ def test_old_absolute_wording_cannot_approve_a_relative_service_gate(campaign): old_brief = dict(gate["task_brief"]) old_brief.pop("id") old_brief["quality_gate"] = "quality <= 0.1 points" + old_fields = old_brief["conditions"] + old_fields["protocol.quality_limit"] = old_fields.pop("protocol.quality_baseline_tolerance") + for key in ("quality_reference", "quality_direction", "quality_mode"): + old_fields.pop("protocol." + key) payload = json.dumps(old_brief, ensure_ascii=False, sort_keys=True, separators=(",", ":")) old_id = "q:task_brief:" + hashlib.sha256(payload.encode()).hexdigest() record["brief_decision"]["question"] = old_id @@ -1604,5 +1625,25 @@ def test_old_absolute_wording_cannot_approve_a_relative_service_gate(campaign): assert main(args) == 2 reopened = json.loads(campaign["capsys"].readouterr().out) assert reopened["brief_review"] == "awaiting_confirmation" - assert "baseline quality - 0.1 points" in reopened["task_brief"]["quality_gate"] + assert "baseline quality + 0.1 points" in reopened["task_brief"]["quality_gate"] + assert not campaign["root"].exists() + + +def test_legacy_relative_maximize_reopens_comparator_before_a_new_card(campaign): + from inferrsi.apps.cli import task_intake + from tests.fixtures.campaign_intake import approved_start + + config = settings() + config["quality"].pop("threshold") + config["quality"].update(mode="baseline_comparison", tolerance=0.1) + campaign["config"].write_text(json.dumps(config)) + args = approved_start(campaign["start"]) + path = Path(args[-1]) + record = task_intake.read_record(path) + record["fields"]["protocol.quality_comparator"]["value"] = "at_most" + task_intake.write_record(path, record) + assert main(args) == 2 + gate = json.loads(campaign["capsys"].readouterr().out) + assert gate["task_brief"] is None + assert gate["questions"][0]["field"] == "protocol.quality_comparator" assert not campaign["root"].exists() diff --git a/tests/fixtures/campaign_intake.py b/tests/fixtures/campaign_intake.py index 8260550e8..3cdf9b668 100644 --- a/tests/fixtures/campaign_intake.py +++ b/tests/fixtures/campaign_intake.py @@ -46,7 +46,7 @@ def approved_start(arguments, *, overrides=None): else obj["domain"]["min"], "protocol.quality_benchmark": q["dataset"], "protocol.quality_metric": q["key"], - "protocol.quality_comparator": "at_most" if relative else cmp, + "protocol.quality_comparator": cmp, "protocol.quality_limit": q["tolerance" if relative else "threshold"], "protocol.service_lifecycle": "fixture owned process", "optimization.workload": cfg["conditions"]["workload"], From 9f50e9f8656e250b01d78d9d146dc7e51b518046 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:14:53 +0800 Subject: [PATCH 15/26] Mark service quality inputs provisional before the executable plan is bound Show the stated value and unit in planning briefs without claiming an absolute inequality. The prepared card presents the resolved score rule and requires its own decision. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 2 ++ src/inferrsi/apps/cli/intake_contract.py | 6 ++++++ tests/apps/test_project_service_reuse.py | 27 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index f32516f79..7ceffeb72 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -193,6 +193,8 @@ The final approval binds the effective settings, including defaults, candidate inputs, commands, sampling, budget and the evaluation configuration. Running preparation again with the same settings preserves an existing approval. A changed launch needs a fresh card. Planning-only briefs can still be reviewed. +Before service configuration is bound, the brief labels its quality inputs +provisional. Show the prepared inequality on the final card for a measured run. Start rechecks the selected gate and the approved launch before creating the campaign. Missing, stale and mismatched approval exits with status 2. A matching diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index 6aeec7bbd..b73320af7 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -577,6 +577,12 @@ def _performance_brief(record: dict, spec: dict) -> dict: values["protocol.quality_baseline_tolerance"] = values.pop("protocol.quality_limit") values["protocol.quality_reference"] = ( "retained baseline score for the current comparison epoch") + elif values["protocol.comparison"] == "service_reuse": + brief["quality_gate_status"] = "provisional" + brief["quality_gate"] = ( + f"Provisional service quality inputs: {values['protocol.quality_metric']}, " + f"{limit} {values['protocol.quality_unit']}. Prepare the executable plan to show " + "whether this value is an absolute threshold or a tolerance against the baseline.") brief["id"] = _BRIEF_QUESTION + hashlib.sha256(_canonical(brief).encode()).hexdigest() return brief diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 67963ff0e..4122efd33 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1647,3 +1647,30 @@ def test_legacy_relative_maximize_reopens_comparator_before_a_new_card(campaign) assert gate["task_brief"] is None assert gate["questions"][0]["field"] == "protocol.quality_comparator" assert not campaign["root"].exists() + + +def test_service_planning_brief_marks_quality_inputs_provisional(campaign): + from inferrsi.apps.cli import task_intake + from tests.fixtures.campaign_intake import approved_start + + cfg = settings() + cfg["quality"].pop("threshold") + cfg["quality"].update(mode="baseline_comparison", tolerance=0.1) + campaign["config"].write_text(json.dumps(cfg)) + args = approved_start(campaign["start"], overrides={"protocol.quality_unit": "points"}) + path = Path(args[-1]) + record = task_intake.read_record(path) + record.pop("campaign_launch") + record.pop("brief_decision") + task_intake.write_record(path, record) + planning, _ = task_intake.campaign_gate(path) + brief = planning["task_brief"] + assert brief["quality_gate_status"] == "provisional" + assert "Provisional service quality inputs: quality, 0.1 points" in task_intake.render(planning) + assert "quality >= 0.1" not in brief["quality_gate"] + assert main([*args, "--prepare-intake"]) == 0 + prepared = json.loads(campaign["capsys"].readouterr().out) + assert prepared["brief_review"] == "awaiting_confirmation" + assert prepared["task_brief"]["id"] != brief["id"] + assert "quality >= baseline quality - 0.1 points" in prepared["task_brief"]["quality_gate"] + assert not campaign["root"].exists() From 1a005543b28dcf130dd2a26da4f65b5c9d7963a7 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:36:09 +0800 Subject: [PATCH 16/26] Bind AB/BA quality evidence to the approved benchmark identity Freeze the supplied dataset identity before launch and require it on scored results. Reject missing or foreign corpora even when numeric and boolean checks pass. Cover launch mismatches, both invalid receipts and the existing project flows. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- .../optimization-workflow-unification.md | 6 ++- docs/guides/task-intake.md | 5 ++- plugins/inferrsi/skills/inferrsi/SKILL.md | 3 ++ src/inferrsi/apps/cli/arguments.py | 3 ++ src/inferrsi/apps/cli/campaign_intake.py | 5 +-- src/inferrsi/apps/cli/intake_contract.py | 17 +-------- src/inferrsi/apps/cli/task_intake.py | 7 ---- src/inferrsi/harness/optimization_session.py | 4 +- src/inferrsi/harness/project.py | 8 ++++ .../test_engineering_benchmark_plugins.py | 3 +- tests/apps/test_project_explanation.py | 6 ++- tests/apps/test_project_optimization.py | 14 ++++--- tests/apps/test_task_intake.py | 38 ++++++++++++++++--- tests/fixtures/campaign_intake.py | 1 + 14 files changed, 76 insertions(+), 44 deletions(-) diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index d08a7b007..785f3d7e9 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -170,7 +170,7 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 下面是命令结构;尖括号是需要落实的项目条件,不是可直接执行的默认值。命令以 argv 执行,不经 shell;Windows 命令参数中的路径建议用正斜杠。 -Prepare the executable brief and obtain the final card reply as described in [task intake](task-intake.md#campaign-hand-off). +启动前,按[任务确认流程](task-intake.md#campaign-hand-off)准备实际启动参数,复述任务书并等待用户确认。 ```bash inferrsi campaign start --intake --directory \ @@ -179,7 +179,8 @@ inferrsi campaign start --intake --directory --metric-unit --direction \ - --quality-key --scope \ + --quality-benchmark --quality-key \ + --scope \ --min-improvement-pct --warmups --repetitions \ --rounds --round-mode up_to --max-minutes \ --evaluation-timeout-seconds --knowledge on @@ -196,6 +197,7 @@ assessment 另附 `paired_statistics`:同一次重复内的第 k 个基线与 结果协议: - 测量脚本正常结束并写 JSON,提供指定字段的有限正数。 +- 质量脚本在顶层 `dataset` 字段报告实际评分的数据集、版本及切分标识,与已批准的 `--quality-benchmark` 一致。缺少标识或标识不匹配时,质量证据为 `INCONCLUSIVE`。 - 质量脚本正常结束并写 JSON,提供指定字段的严格布尔值。`false` 拒绝候选;基线拒绝说明协议/基线前提不成立。 - 脚本可捕获已知候选错误,正常结束并写 `{"status":"candidate_failure","reason":"..."}`。候选失败保留为 FAIL 并消耗一轮,后续可修改。不要把设备故障捕获成候选错误。 - 非零退出、超时、缺少或无法解析的输出不猜测为正确性失败,而是 INCONCLUSIVE,阻止继续把缺失证据当成有效比较。 diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 7ceffeb72..081ddb9d3 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -203,7 +203,10 @@ preapproval starts unattended. The frozen `plan.json` references a receipt in For AB/BA the two approved measurement commands describe the same script with the candidate path supplied at execution. The quality command returns its -boolean acceptance key and a numeric result under the approved quality metric +identity of the dataset actually scored in the top-level `dataset` field. It must +match both `--quality-benchmark` and the approved benchmark (including its version +and split). Missing or mismatched identity makes the result `INCONCLUSIVE`. +Also return the boolean acceptance key and a numeric result under the approved quality metric (JSON dotted paths are supported). A boolean metric on the acceptance key is compared as 1 or 0. The independent final checks the approved absolute bound or relative improvement against the pinned baseline. For service reuse, the first diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index bee9a8c2c..ef146c194 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -141,6 +141,9 @@ Declare every execution input with repeatable `--include`; freeze scripts and inputs through `--protocol`. Checks must use the retained `{candidate}`, `{baseline}`, `{protocol}` and output `{result}` paths as appropriate. Confirm they execute the submitted code, not an unrelated installed package or service. +For AB/BA, pass the approved dataset version and split as `--quality-benchmark`. +The quality script must report the identity of the corpus it actually scored in +the top-level `dataset` field alongside the quality result. This command uses the same Harness controller as the packaged task path below. Edit the returned working candidate. Submit each hypothesis and candidate with diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index c77edf282..03896bdfd 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -196,6 +196,9 @@ def _optimization_actions(stages, *, project=False): for name in ("measure-command", "quality-command", "metric-key", "metric-unit", "quality-key", "scope"): start.add_argument("--" + name) + start.add_argument("--quality-benchmark", + help="AB/BA dataset identity (including version/split) reported " + "by the quality script") start.add_argument("--direction", choices=("minimize", "maximize")) start.add_argument("--min-improvement-pct", type=float) start.add_argument("--repetitions", type=int) diff --git a/src/inferrsi/apps/cli/campaign_intake.py b/src/inferrsi/apps/cli/campaign_intake.py index b187effc8..7cdf7b957 100644 --- a/src/inferrsi/apps/cli/campaign_intake.py +++ b/src/inferrsi/apps/cli/campaign_intake.py @@ -16,8 +16,6 @@ def _blocked(reason, **details): def _execution(plan, args, staged): - # Retain the settings actually produced by Harness (including defaulted options). - # Implementation version fingerprints do not describe the user's execution choices. launch = { key: value for key, value in plan.items() @@ -68,6 +66,7 @@ def _execution(plan, args, staged): "acceptance.metric_unit": settings["metric_unit"], "acceptance.direction": settings["direction"], "acceptance.min_improvement_pct": settings["min_improvement_pct"], + "protocol.quality_benchmark": settings["quality_benchmark"], "protocol.timing_boundary": settings["scope"], "environment.repetitions": settings["repetitions"], } @@ -100,7 +99,6 @@ def _conflicts(conditions, expected, args): and approved != actual and (args.repo / ".git").exists() ): - # A Git pin also requires that the retained inputs belong to that commit. if actual == candidates.identity(args.repo, args.include): actual = project_service.revision(args.repo, args.include) if approved != actual: @@ -160,7 +158,6 @@ def _initialize(staged, destination, plan, record, gate): settings = plan["evaluation_settings"] primary = next(obj for obj in settings["objectives"] if obj["id"] == settings["ranking"][0]) if primary["threshold_type"] != "relative_percent": - # A native absolute/point gain cannot stand in for the reviewed percentage gate. plan["candidate_min_improvement_pct"] = conditions["acceptance.min_improvement_pct"] else: plan["evaluation_settings"]["quality_bound"] = { diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index b73320af7..ce197875d 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -23,8 +23,6 @@ SCHEMA_VERSION = 1 -# Stage vocabulary. ``read_only_preparation`` is always allowed; the others are -# unlocked only when no field declared ``required_before`` that stage is missing. STAGES = ( "read_only_preparation", "baseline_measurement", @@ -34,7 +32,6 @@ ) BLOCKING_STAGES = STAGES[1:] -# Where each field lands when a record is handed to an execution entry. MAP_TARGETS = ("task-input/v1", "campaign-protocol", "session-protocol", "summary-only", "day0-spec") @@ -44,7 +41,6 @@ BLOCKING = ("unknown", "assumed", "conflicting", "stale", "superseded") ACCEPTANCE = "acceptance." -# An issue or file can supply acceptance values only for a user-selected reference. AUTHORITATIVE = ("issue", "frozen_gate") REFERENCE = "acceptance.reference" @@ -349,8 +345,6 @@ def reconcile_record(record: dict, spec: dict) -> dict: try: _coerce(field, entry.get("value")) except IntakeError: - # Older intakes accepted out-of-range execution values. Keep their - # provenance and reissue the field question before another brief. updated["fields"][path] = {"value": None, "status": "unknown", "source": entry["source"], "rejected_value": entry.get("value")} @@ -363,7 +357,6 @@ def reconcile_record(record: dict, spec: dict) -> dict: if quality and quality["mode"] == "baseline_comparison" and comparator["status"] in SETTLED: expected = "at_least" if quality["direction"] == "maximize" else "at_most" if comparator["value"] != expected: - # Legacy maximize approvals used the comparator for the tolerance. updated["fields"]["protocol.quality_comparator"] = { "value": None, "source": comparator["source"], "status": "conflicting", "candidates": [{"value": comparator["value"], "source": comparator["source"]}, @@ -417,14 +410,12 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: current.get("value") == value ): if _rank(status) <= _rank(current.get("status", "unknown")): - continue # same value, no stronger source: leave the record unchanged + continue updated["fields"][path] = entry changed = True continue if (current is not None and current.get("status") == "conflicting" and isinstance(current.get("candidates"), list)): - # Only an explicit answer settles an open choice. Repeated imports - # can supply another option but cannot reselect one on the user's behalf. if all(item["value"] != value for item in current["candidates"]): current["candidates"].append({"value": value, "source": source}) changed = True @@ -436,7 +427,7 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: updated["fields"][path] = entry changed = True elif _rank(status) < _rank(current["status"]): - continue # the accepted value wins over a later proposal + continue else: updated["fields"][path] = {"value": None, "source": source, "status": "conflicting", @@ -645,8 +636,6 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: if blocked_by: blockers.append({"stage": stage, "blocked_by": blocked_by}) if conflicts: - # A gate mismatch blocks candidate search even when every stated field - # is otherwise settled: the accepted record is no longer the same gate. entries = [{"field": item["field"], "status": "conflicting"} for item in conflicts] existing = next((item for item in blockers if item["stage"] == "candidate_search"), None) @@ -676,8 +665,6 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: blockers.append(blocker) blocker["blocked_by"].append({"field": "task_brief", "status": review}) blocked_stages = {item["stage"] for item in blockers} - # Device and service execution always need a separate authorization; the - # record only unlocks preparation, baseline measurement and candidate search. allowed_next = ["read_only_preparation"] + [ stage for stage in ("baseline_measurement", "candidate_search") if stage not in blocked_stages diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 88988dcf3..1ee0ba447 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -84,8 +84,6 @@ def frozen_values(path: Path) -> dict: raise intake.IntakeError( "invalid_frozen", f"frozen gate record: {first['field']} {first['message']}") acceptance = preview["task"]["acceptance"] - # ``reference`` names the gate record itself and is path-normalized by the task - # contract, so it is not compared; ``task_input.frozen_gate`` makes the same choice. return {f"acceptance.{name}": value for name, value in acceptance.items() if name != "reference" and preview["sources"][f"acceptance.{name}"] == "yaml"} @@ -128,7 +126,6 @@ def _evaluate_gate(record: dict, spec: dict, frozen_path: Path | None, record["selected_gate"] = snapshot record["selected_gate_file"] = str(frozen_path.resolve()) if record.get("selected_gate") == snapshot: - # Preserve disagreements for the frozen-gate comparison. matching = {} for field in spec["fields"]: key = field["path"] @@ -138,8 +135,6 @@ def _evaluate_gate(record: dict, spec: dict, frozen_path: Path | None, matching[key] = frozen[key] record = intake.set_fields(record, spec, matching, source="frozen_gate") else: - # The file is new or changed since the selection. Re-open the reference - # question and persist the revocation before handing off to campaign start. record.pop("selected_gate", None) record.pop("selected_gate_file", None) record.pop("brief_decision", None) @@ -182,8 +177,6 @@ def evaluate_command(args) -> dict: if intake.evaluate(record, spec)["brief_review"] != "changes_requested": raise intake.IntakeError("user_answer_required", "Use the reference question to record the user's reply") - # An explicit correction to a returned brief replaces the reference. Values - # sourced from its former authority must be obtained from the new selection. previous = intake.selected_reference(record) record["fields"] = {key: entry for key, entry in record["fields"].items() if key != intake.REFERENCE and not ( diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 3ef1e569f..cadbf0b31 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -171,6 +171,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None "metric_key", "metric_unit", "quality_key", + "quality_benchmark", "scope", "direction", "min_improvement_pct", @@ -231,7 +232,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None raise ValueError("Campaign output must be outside the editable project") identity(repo, args.include) # Reject invalid inputs before preparation writes. specification = {key: getattr(args, key) for key in ( - "metric_key", "metric_unit", "quality_key", "scope", "direction", + "metric_key", "metric_unit", "quality_key", "quality_benchmark", "scope", + "direction", "min_improvement_pct", "repetitions", "warmups", "decision", "require_explanation")} specification.update(measure_command=shlex.split(args.measure_command), diff --git a/src/inferrsi/harness/project.py b/src/inferrsi/harness/project.py index f1622844d..8ef705636 100644 --- a/src/inferrsi/harness/project.py +++ b/src/inferrsi/harness/project.py @@ -28,6 +28,10 @@ def validate(settings: dict) -> None: for key in ("metric_key", "metric_unit", "quality_key", "scope"): if not isinstance(settings[key], str) or not settings[key].strip(): raise ValueError(f"An explicit {key} is required") + if "quality_benchmark" in settings and not ( + isinstance(settings["quality_benchmark"], str) and settings["quality_benchmark"].strip() + ): + raise ValueError("An explicit quality benchmark identity is required") if settings["direction"] not in ("minimize", "maximize"): raise ValueError("Metric direction must be explicit") if type(settings["repetitions"]) is not int or settings["repetitions"] < 1: @@ -128,6 +132,10 @@ def inspect_step(directory: Path, settings: dict, definition: dict, execution: d return {**failure, "reason": "missing_or_invalid_result"} evidence = {relative: sha256(path)} rejected = document.get("status") == "candidate_failure" + benchmark = settings.get("quality_benchmark") + if (definition["phase"] == "quality" and benchmark is not None and not rejected + and document.get("dataset") != benchmark): + return {**failure, "reason": "quality_benchmark_mismatch", "evidence_files": evidence} quality = _value(document, settings["quality_key"]) bound = settings.get("quality_bound") if definition["phase"] == "quality" and bound and quality is True: diff --git a/tests/apps/test_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py index bd7db6544..c0c748fa5 100644 --- a/tests/apps/test_engineering_benchmark_plugins.py +++ b/tests/apps/test_engineering_benchmark_plugins.py @@ -74,7 +74,8 @@ def test_isolated_plugin_runs_project_round_and_retained_final(distribution, tmp "--measure-command", '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "synthetic-units", "--direction", "maximize", - "--quality-key", "correct", "--scope", "synthetic-software-control", + "--quality-benchmark", "fixture-exact-v1", "--quality-key", "correct", + "--scope", "synthetic-software-control", "--min-improvement-pct", "1", "--warmups", "0", "--repetitions", "1", "--rounds", "1", "--max-minutes", "5", "--evaluation-timeout-seconds", "30", "--python", "python3"]), diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index a556aaea1..aa86a038b 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -47,7 +47,8 @@ def project(tmp_path): (protocol / "quality.py").write_text( "import json, runpy, sys\nfrom pathlib import Path\n" "compute = runpy.run_path(str(Path(sys.argv[1])/'engine.py'))['compute']\n" - "Path(sys.argv[2]).write_text(json.dumps({'correct':compute(16)==32}))\n", + "result = {'correct':compute(16)==32,'dataset':'fixture-exact-v1'}\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n", encoding="utf-8", ) instructions = tmp_path / "task.md" @@ -64,7 +65,8 @@ def start(project, capsys, *extra, repetitions=8): '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "ms", "--direction", "minimize", - "--quality-key", "correct", "--scope", "synthetic-software-control", + "--quality-benchmark", "fixture-exact-v1", "--quality-key", "correct", + "--scope", "synthetic-software-control", "--repetitions", str(repetitions), "--warmups", "1", "--min-improvement-pct", "1", "--rounds", "4", "--round-mode", "up_to", "--max-minutes", "5", "--evaluation-timeout-seconds", "20", *extra, diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 27defac60..3f1338fbe 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -34,7 +34,8 @@ def project(tmp_path): (protocol / "quality.py").write_text( "import json, runpy, sys\nfrom pathlib import Path\n" "compute = runpy.run_path(str(Path(sys.argv[1])/'engine.py'))['compute']\n" - "Path(sys.argv[2]).write_text(json.dumps({'correct':compute(16)==32}))\n", + "result = {'correct':compute(16)==32,'dataset':'fixture-exact-v1'}\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n", encoding="utf-8", ) instructions = tmp_path / "task.md" @@ -52,7 +53,8 @@ def start_arguments(project, *, direction="maximize", mode="up_to", extra=()): '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "synthetic-units", "--direction", direction, - "--quality-key", "correct", "--scope", "synthetic-software-control", + "--quality-benchmark", "fixture-exact-v1", "--quality-key", "correct", + "--scope", "synthetic-software-control", "--repetitions", "2", "--warmups", "1", "--min-improvement-pct", "1", "--rounds", "3", "--round-mode", mode, "--max-minutes", "5", "--evaluation-timeout-seconds", "20", *extra, @@ -274,7 +276,8 @@ def test_dashboard_rejects_identical_bytes_when_earlier_round_remains_best( "import json, sys\nfrom pathlib import Path\n" "result = Path(sys.argv[2])\n" "rejected = 'round-02' in result.parts and 'quality-candidate' in result.parts\n" - "result.write_text(json.dumps({'correct':not rejected}))\n", + "checked = {'correct':not rejected,'dataset':'fixture-exact-v1'}\n" + "result.write_text(json.dumps(checked))\n", encoding="utf-8", ) start(project, capsys) @@ -527,7 +530,7 @@ def test_bad_candidate_exception_is_classified_by_frozen_wrapper(project, capsys "import json, runpy, sys\nfrom pathlib import Path\n" "try:\n" " compute = runpy.run_path(str(Path(sys.argv[1])/'engine.py'))['compute']\n" - " result = {'correct':compute(16)==32}\n" + " result = {'correct':compute(16)==32,'dataset':'fixture-exact-v1'}\n" "except RuntimeError:\n" " result = {'status':'candidate_failure', 'reason':'compute raised RuntimeError'}\n" "Path(sys.argv[2]).write_text(json.dumps(result))\n", encoding="utf-8") @@ -659,7 +662,8 @@ def test_dashboard_shows_failed_independent_final_separately_from_search( "# Synthetic final-only rejection exercises result presentation, not quality policy.\n" "passed = not ('final' in Path(sys.argv[2]).parts and " f"Path(sys.argv[1]).name == {side!r})\n" - "Path(sys.argv[2]).write_text(json.dumps({'correct':passed}))\n", encoding="utf-8") + "result = {'correct':passed,'dataset':'fixture-exact-v1'}\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n", encoding="utf-8") start(project, capsys) submit(project, capsys, 20) assert main(["campaign", "final", "--directory", str(project[3]), diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index 6b8d45924..4a9776b40 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -327,7 +327,7 @@ def test_frozen_values_read_the_gate_task_file(): values = task_intake.frozen_values(PERFORMANCE / "frozen-gate.yaml") assert values["acceptance.metric_key"] == "p95_ttft" assert values["acceptance.min_improvement_pct"] == 10.0 - assert "acceptance.reference" not in values # names the record; never compared + assert "acceptance.reference" not in values def test_matching_frozen_gate_keeps_a_complete_record_complete(): @@ -379,7 +379,6 @@ def test_campaign_start_retains_the_record_it_gated(project, tmp_path, capsys): assert json.loads(retained.read_bytes()) == json.loads(record.read_bytes()) plan = json.loads((project[3] / "plan.json").read_bytes()) assert json.loads((project[3] / plan["intake_receipt"]).read_bytes()) == result["intake"] - # The retained record does not disturb the managed campaign's own records. assert cli.main(["campaign", "status", "--directory", str(project[3])]) == 0 @@ -467,8 +466,6 @@ def test_self_written_gate_keeps_campaign_blocked(project, tmp_path, capsys): # capsys.readouterr() assert not project[3].exists() - # Records written before this fix may already say every workspace/gate value - # was confirmed and cache a complete result. The execution path must recheck. record = json.loads(record_path.read_text()) for field in record["fields"].values(): field["status"] = "confirmed" @@ -485,7 +482,6 @@ def test_selected_gate_imports_only_its_values_and_changed_file_reopens_card(tmp assert cli.main([*cmd, "--task", "task-performance"]) == 0 capsys.readouterr() - # This is the separate reply to the outstanding reference question. answer = ["task", "intake", "answer", "--record", str(record), "--question", "q:acceptance.reference", "--value", str(gate), "--frozen", str(gate), "--json"] assert cli.main(answer) == 0 @@ -712,6 +708,7 @@ def test_loaded_approved_record_reopens_unusable_execution_values(project, tmp_p ("--measure-command", "{python} {protocol}/different.py {result}", "launch_conflict"), ("--rounds", "2", "launch_conflict"), ("--quality-key", "different", "launch_changed"), + ("--quality-benchmark", "wrong-corpus", "launch_conflict"), ("--warmups", "7", "launch_changed"), ]) def test_changed_launch_never_creates_campaign(project, capsys, flag, value, reason): # noqa: F811 @@ -777,7 +774,8 @@ def test_boolean_quality_success_does_not_override_numeric_limit(project, capsys (project[1] / "quality.py").write_text( "import json, sys\nfrom pathlib import Path\n" "value = json.loads((Path(sys.argv[1])/'config.json').read_text())['metric']\n" - "Path(sys.argv[2]).write_text(json.dumps({'correct':True,'errors':value-10}))\n") + "result = {'correct':True,'errors':value-10,'dataset':'fixture-exact-v1'}\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n") args = approved_start(start_arguments(project), overrides={ "protocol.quality_metric": "errors", "protocol.quality_limit": 0, "protocol.quality_comparator": "at_most", "protocol.quality_unit": "tokens"}) @@ -788,3 +786,31 @@ def test_boolean_quality_success_does_not_override_numeric_limit(project, capsys _, view = submit(project, capsys, 20) assert view["best"]["kind"] == "baseline" assert view["latest_observation"]["assessment"]["quality_passed"] is False + + +@pytest.mark.parametrize("reported", ["wrong-corpus", None]) +def test_abba_quality_rejects_foreign_or_missing_corpus(project, capsys, reported): # noqa: F811 + from tests.apps.test_project_optimization import submit + from tests.fixtures.diagnosis import diagnosis_args + + (project[1] / "quality.py").write_text( + "import json, sys\nfrom pathlib import Path\n" + "result = {'correct':True,'accuracy':100,'dataset':'fixture-exact-v1'}\n" + "if Path(sys.argv[1]).name == 'candidate':\n" + f" result['dataset'] = {reported!r}\n" + " if result['dataset'] is None: del result['dataset']\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n") + args = approved_start(start_arguments(project), overrides={ + "protocol.quality_metric": "accuracy", "protocol.quality_limit": 95, + "protocol.quality_comparator": "at_least", "protocol.quality_unit": "points"}) + assert cli.main(args) == 0 + capsys.readouterr() + plan = json.loads((project[3] / "plan.json").read_bytes()) + assert plan["evaluation_settings"]["quality_benchmark"] == "fixture-exact-v1" + assert cli.main(diagnosis_args(project[3], "campaign")) == 0 + capsys.readouterr() + code, result = submit(project, capsys, 20) + assessment = result["latest_observation"]["assessment"] + assert code == 2 and result["best"]["kind"] == "baseline" + assert (assessment["verdict"], assessment["reason"]) == ( + "INCONCLUSIVE", "quality_benchmark_mismatch") diff --git a/tests/fixtures/campaign_intake.py b/tests/fixtures/campaign_intake.py index 3cdf9b668..d5d0aa01f 100644 --- a/tests/fixtures/campaign_intake.py +++ b/tests/fixtures/campaign_intake.py @@ -67,6 +67,7 @@ def approved_start(arguments, *, overrides=None): "acceptance.direction": args.direction, "acceptance.min_improvement_pct": args.min_improvement_pct, "protocol.target_value": 10000 if args.direction == "minimize" else 0, + "protocol.quality_benchmark": args.quality_benchmark, "protocol.quality_metric": args.quality_key, "protocol.quality_comparator": "equal", "protocol.quality_limit": 1, From f30813e4c40481df4f68a39f9664641f56b4338c Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:42:31 +0800 Subject: [PATCH 17/26] Clarify the evidence used for scored AB/BA quality results Document the self-reported dataset label and the separate verdict for an explicit unscored rejection. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/optimization-workflow-unification.md | 2 +- docs/guides/task-intake.md | 14 +++++++++----- plugins/inferrsi/skills/inferrsi/SKILL.md | 5 +++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 785f3d7e9..18cde2bd7 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -197,7 +197,7 @@ assessment 另附 `paired_statistics`:同一次重复内的第 k 个基线与 结果协议: - 测量脚本正常结束并写 JSON,提供指定字段的有限正数。 -- 质量脚本在顶层 `dataset` 字段报告实际评分的数据集、版本及切分标识,与已批准的 `--quality-benchmark` 一致。缺少标识或标识不匹配时,质量证据为 `INCONCLUSIVE`。 +- 对于有评分的结果,质量脚本在顶层 `dataset` 字段自行报告数据集、版本和切分标识。Harness 将它与已批准的 `--quality-benchmark` 核对;缺少标识或标识不一致时,该评分结果为 `INCONCLUSIVE`。 - 质量脚本正常结束并写 JSON,提供指定字段的严格布尔值。`false` 拒绝候选;基线拒绝说明协议/基线前提不成立。 - 脚本可捕获已知候选错误,正常结束并写 `{"status":"candidate_failure","reason":"..."}`。候选失败保留为 FAIL 并消耗一轮,后续可修改。不要把设备故障捕获成候选错误。 - 非零退出、超时、缺少或无法解析的输出不猜测为正确性失败,而是 INCONCLUSIVE,阻止继续把缺失证据当成有效比较。 diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 081ddb9d3..e82583966 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -202,11 +202,15 @@ preapproval starts unattended. The frozen `plan.json` references a receipt in `plan/` with the SHA-256 and revision of the retained `intake.json`. For AB/BA the two approved measurement commands describe the same script with -the candidate path supplied at execution. The quality command returns its -identity of the dataset actually scored in the top-level `dataset` field. It must -match both `--quality-benchmark` and the approved benchmark (including its version -and split). Missing or mismatched identity makes the result `INCONCLUSIVE`. -Also return the boolean acceptance key and a numeric result under the approved quality metric +the candidate path supplied at execution. For a scored quality check, the +frozen script self-reports the dataset it evaluated in the top-level `dataset` +field. Harness compares that label with the approved `--quality-benchmark`, +including its version and split. The script supplies the evidence for which +corpus it loaded. A missing or mismatched label makes a scored result +`INCONCLUSIVE`. An explicit `status: candidate_failure` is an unscored +rejection. A candidate rejection is `FAIL`, and a baseline rejection leaves +the comparison `INCONCLUSIVE`. A scored result also supplies the boolean +acceptance key and a numeric result under the approved quality metric (JSON dotted paths are supported). A boolean metric on the acceptance key is compared as 1 or 0. The independent final checks the approved absolute bound or relative improvement against the pinned baseline. For service reuse, the first diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index ef146c194..e6118cc2e 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -142,8 +142,9 @@ inputs through `--protocol`. Checks must use the retained `{candidate}`, `{baseline}`, `{protocol}` and output `{result}` paths as appropriate. Confirm they execute the submitted code, not an unrelated installed package or service. For AB/BA, pass the approved dataset version and split as `--quality-benchmark`. -The quality script must report the identity of the corpus it actually scored in -the top-level `dataset` field alongside the quality result. +For a scored result, the quality script self-reports the corpus it evaluated in +the top-level `dataset` field. Harness checks the reported label against the +approved identity. This command uses the same Harness controller as the packaged task path below. Edit the returned working candidate. Submit each hypothesis and candidate with From d8131f62dad69e63c81562f2ffa4c626b676bf9c Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 16:53:54 +0800 Subject: [PATCH 18/26] Assert corpus identity in the ranking-policy quality parity test Compare the complete scored receipt across both policy arms, including the approved fixture dataset. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- tests/apps/test_session_ranking_policy.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 2b5b0b61a..13c2ed327 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -167,7 +167,8 @@ def test_project_assessor_uses_the_same_measurements_quality_and_threshold(proje assert assessment["verdict"] == "PASS" and assessment["quality_passed"] directory = arm[-1] / read(arm[-1] / "state.json")["rounds"][0]["path"] samples = {p.parent.name: read(p) for p in (directory / "execution").glob("*/result.json")} - assert {"metric": 20} in samples.values() and {"correct": True} in samples.values() + assert {"metric": 20} in samples.values() + assert {"correct": True, "dataset": "fixture-exact-v1"} in samples.values() evidence.append((read(arm[-1] / "plan.json")["evaluation_settings"], samples, assessment["verdict"], assessment["score"], assessment["quality_passed"])) assert evidence[0] == evidence[1] From 7407ab7153221e264be8e41c818476bc41b97907 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 19:54:53 +0800 Subject: [PATCH 19/26] Enforce the approved quality score unit during campaign evaluation Bind the AB/BA numeric gate before approval and compare the service quality scale with the task brief. Normalize explicitly labelled proportions and percentages before applying absolute gates or additive baseline tolerances. Reject incompatible receipts and retain the raw evidence for replay. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/service-reuse-campaigns.md | 12 +++- docs/guides/task-intake.md | 8 ++- plugins/inferrsi/skills/inferrsi/SKILL.md | 4 +- src/inferrsi/apps/cli/campaign_intake.py | 13 ++-- src/inferrsi/apps/cli/intake_contract.py | 2 + src/inferrsi/harness/project.py | 27 +++++++- src/inferrsi/harness/project_service.py | 13 ++-- tests/apps/test_project_service_reuse.py | 64 ++++++++++++++++++- tests/apps/test_task_intake.py | 38 ++++++++++- tests/fixtures/campaign_intake.py | 1 + tests/fixtures/service_reuse.py | 1 + tests/fixtures/service_reuse_protocol.py | 1 + .../test_service_reference_evidence.py | 1 + 13 files changed, 162 insertions(+), 23 deletions(-) diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index cfe8f8b34..60abe54d5 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -36,7 +36,7 @@ Supply a JSON file with these fields; every threshold and workload is explicit: | `scenarios` | Objects declaring unique string `id`, `workload`, positive integer `requests`, and positive integer `required_successes` no greater than requests | | `objectives` | Objects described below; at least one participates in gain assessment | | `ranking` | Unique objective IDs in priority order | -| `quality` | `mode`, `dataset`, `scorer`, `key`, `direction`, positive integer `samples`, plus the corresponding quality gate | +| `quality` | `mode`, `dataset`, `scorer`, `key`, `unit`, `direction`, positive integer `samples`, plus the corresponding quality gate | | `stagnation` | `{"disabled": true}`, or positive integer `rounds` and `action` equal to `advisory` or `pause` | | `screening` | Optional argv `command` and positive `estimated_gain`; the estimate never replaces a formal gate | @@ -50,7 +50,13 @@ thresholds for negative-valued domains. For quality, `absolute` requires `threshold`. `baseline_comparison` requires nonnegative `tolerance` and compares with the compatible retained baseline score. -By default the baseline service collects the reference after its performance. +The approved `quality.unit` is the scale for the threshold and the additive +tolerance. Each scored receipt, including an external baseline reference, reports +its own `unit`. The harness converts `fraction` / `ratio` and `%` / `percent` +to the approved scale before storing the score. Other units must match exactly. +Unknown or incompatible units produce `INCONCLUSIVE`. A baseline tolerance in +`%` specifies percentage points. By default the baseline service collects the +reference after its performance. An optional `reference_path` points inside the retained protocol to a compatible existing baseline quality result. In addition to the quality-result fields, that result declares `revision`, `conditions`, `service_id`, and `run_id`. @@ -85,7 +91,7 @@ Harness checks service liveness and binding between stages. Each measurement result contains `scenarios[scenario_id]` with `workload`, actual `requests`, `successes`, the declared metric fields, and `units[objective_id]`. Every repetition covers every required scenario. Warmup results are separate. -Quality results contain `dataset`, `scorer`, `samples`, and the declared numeric +Quality results contain `dataset`, `scorer`, `samples`, `unit`, and the declared numeric score field. An explicit `status: candidate_failure` from precheck/quality is a rejection; crashes, absent evidence and incompatible results are INCONCLUSIVE. diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index e82583966..91a814343 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -212,7 +212,13 @@ rejection. A candidate rejection is `FAIL`, and a baseline rejection leaves the comparison `INCONCLUSIVE`. A scored result also supplies the boolean acceptance key and a numeric result under the approved quality metric (JSON dotted paths are supported). A boolean metric on the acceptance key is -compared as 1 or 0. The independent final checks the approved absolute bound or +compared as 1 or 0 when its approved unit is `boolean`. Numeric quality results +declare their scale in the top-level `unit` field. Both campaign modes compare the +score in the unit on the final card. The harness converts between `fraction` / +`ratio` and `%` / `percent`; other units must match exactly. Missing or +incompatible numeric units give `INCONCLUSIVE`. Service baseline tolerances +are additive in the approved score unit. For percent scores, a tolerance +of one permits a difference of one percentage point. The independent final checks the approved absolute bound or relative improvement against the pinned baseline. For service reuse, the first ranked objective names the final metric and the configuration supplies its dataset, score key, threshold or allowed degradation, commands and sampling. diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index e6118cc2e..5706acc5d 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -144,7 +144,9 @@ they execute the submitted code, not an unrelated installed package or service. For AB/BA, pass the approved dataset version and split as `--quality-benchmark`. For a scored result, the quality script self-reports the corpus it evaluated in the top-level `dataset` field. Harness checks the reported label against the -approved identity. +approved identity. Include the score's `unit` on numeric quality receipts for +both AB/BA and service reuse. Show the approved score scale and, for a service +baseline tolerance on percent scores, the allowed difference in percentage points. This command uses the same Harness controller as the packaged task path below. Edit the returned working candidate. Submit each hypothesis and candidate with diff --git a/src/inferrsi/apps/cli/campaign_intake.py b/src/inferrsi/apps/cli/campaign_intake.py index 7cdf7b957..7c1183b8a 100644 --- a/src/inferrsi/apps/cli/campaign_intake.py +++ b/src/inferrsi/apps/cli/campaign_intake.py @@ -44,6 +44,7 @@ def _execution(plan, args, staged): "acceptance.metric_unit": primary["unit"], "acceptance.direction": primary["direction"], "protocol.quality_metric": quality["key"], + "protocol.quality_unit": quality["unit"], "protocol.quality_benchmark": quality["dataset"], "protocol.quality_comparator": comparison, "protocol.quality_limit": quality["tolerance" if relative else "threshold"], @@ -133,8 +134,13 @@ def start(args, run_session): staged_args.session = Path(tmp) / "campaign" frozen = run_session(staged_args, initialize=lambda _, plan: {"plan": plan}) plan = frozen["plan"] - launch, expected = _execution(plan, args, staged_args.session) brief = gate["task_brief"] + if args.evaluation_mode == "abba": + plan["evaluation_settings"]["quality_bound"] = { + key: brief["conditions"]["protocol.quality_" + key] + for key in ("metric", "comparator", "limit", "unit") + } + launch, expected = _execution(plan, args, staged_args.session) conflicts = _conflicts(brief["conditions"], expected, args) if conflicts: return _blocked("launch_conflict", conflicts=conflicts) @@ -159,11 +165,6 @@ def _initialize(staged, destination, plan, record, gate): primary = next(obj for obj in settings["objectives"] if obj["id"] == settings["ranking"][0]) if primary["threshold_type"] != "relative_percent": plan["candidate_min_improvement_pct"] = conditions["acceptance.min_improvement_pct"] - else: - plan["evaluation_settings"]["quality_bound"] = { - name: conditions["protocol.quality_" + name] - for name in ("metric", "comparator", "limit") - } receipt = task_intake.attach_record(staged, record, gate)["intake"] relative = "plan/intake-" + receipt["sha256"] + ".json" task_intake.write_record(staged / relative, receipt) diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index ce197875d..ce0c68687 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -533,6 +533,8 @@ def _service_quality_line(quality: dict, unit: str) -> str: return f"{metric} {operator} {limit} {unit} (absolute threshold; {direction})" tolerance = str(quality["tolerance"]).removesuffix(".0") sign = "-" if higher else "+" + if unit in ("%", "percent"): + unit = "percentage point" if quality["tolerance"] == 1 else "percentage points" return (f"{metric} {operator} baseline {metric} {sign} {tolerance} {unit} " f"(baseline comparison; {direction}; reference: retained baseline score " "for the current comparison epoch)") diff --git a/src/inferrsi/harness/project.py b/src/inferrsi/harness/project.py index 8ef705636..ca7881199 100644 --- a/src/inferrsi/harness/project.py +++ b/src/inferrsi/harness/project.py @@ -7,6 +7,7 @@ import json import math import shutil +from decimal import Decimal from pathlib import Path from statistics import median @@ -115,6 +116,23 @@ def meets_target(target, *, baseline, candidate, direction): return (change if direction == "maximize" else -change) >= target["target_value"] +def quality_score_in_unit(score, reported_unit, approved_unit): + """Return the score in the frozen unit; only proportional scales can cross units.""" + unspecified = ("", "unknown", "unspecified", "n/a") + for unit in (reported_unit, approved_unit): + if not isinstance(unit, str) or unit.strip().lower() in unspecified: + raise ValueError("quality_unit_mismatch") + if reported_unit == approved_unit: + return score + scales = {"%": 2, "percent": 2, "fraction": 0, "ratio": 0} + if reported_unit not in scales or approved_unit not in scales: + raise ValueError("quality_unit_mismatch") + converted = float(Decimal(str(score)).scaleb(scales[approved_unit] - scales[reported_unit])) + if not math.isfinite(converted): + raise ValueError("quality_unit_mismatch") + return converted + + def inspect_step(directory: Path, settings: dict, definition: dict, execution: dict) -> dict: """Interpret one frozen script's explicit result, never guess a crash's cause.""" failure = {"status": "infrastructure_failure", "reason": "failed_execution"} @@ -140,11 +158,18 @@ def inspect_step(directory: Path, settings: dict, definition: dict, execution: d bound = settings.get("quality_bound") if definition["phase"] == "quality" and bound and quality is True: score = _value(document, bound["metric"]) - if type(score) is bool and bound["metric"] == settings["quality_key"]: + unit = document.get("unit") + if (type(score) is bool and bound["metric"] == settings["quality_key"] + and bound.get("unit") == "boolean"): + unit = document.get("unit", "boolean") score = int(score) if type(score) not in (float, int) or not math.isfinite(score): return {**failure, "reason": "missing_numeric_quality_evidence", "evidence_files": evidence} + try: + score = quality_score_in_unit(score, unit, bound.get("unit")) + except ValueError as exc: + return {**failure, "reason": str(exc), "evidence_files": evidence} limit = bound["limit"] quality = {"at_least": score >= limit, "at_most": score <= limit, "equal": score == limit}[ bound["comparator"]] diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index 1b7a7b564..0092342ea 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -11,11 +11,13 @@ import subprocess import time import uuid +from decimal import Decimal from pathlib import Path from statistics import mean, median from .atomic_json import atomic_write_json from .candidates import members, retain +from .project import meets_target, quality_score_in_unit INLINE_PROFILE_REASONS = ("fixed_checks_satisfied", "performance_gate_not_met") @@ -200,10 +202,10 @@ def validate(settings): or quality.get("direction") not in ("minimize", "maximize") or not all( isinstance(quality.get(key), str) and quality[key].strip() - for key in ("key", "dataset", "scorer") + for key in ("key", "dataset", "scorer", "unit") ) ): - raise ValueError("Declare quality mode, direction, dataset, scorer and key") + raise ValueError("Declare quality mode, direction, dataset, scorer, unit and key") gate = "threshold" if quality["mode"] == "absolute" else "tolerance" if type(quality.get("samples")) is not int or quality["samples"] < 1: raise ValueError("Declare the required quality sample count") @@ -346,7 +348,7 @@ def quality_score(settings, document): or document["samples"] != config["samples"] ): raise ValueError("Missing numerical quality evidence") - return score + return quality_score_in_unit(score, document.get("unit"), config.get("unit")) def quality_passed(settings, score, reference=None): @@ -356,7 +358,8 @@ def quality_passed(settings, score, reference=None): return sign * (score - config["threshold"]) >= 0 if reference is None or not number(reference): raise ValueError("Missing compatible baseline quality reference") - return sign * (score - reference) >= -config["tolerance"] + delta = Decimal(str(score)) - Decimal(str(reference)) + return sign * delta >= -Decimal(str(config["tolerance"])) def revision(source, includes): @@ -865,8 +868,6 @@ def evaluate(role): elif role == "final": target = plan.get("performance_target") if target and gate["passed"]: - from .project import meets_target - name = settings["ranking"][0] objective = next(obj for obj in settings["objectives"] if obj["id"] == name) gate["passed"] = meets_target( diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 4122efd33..649c057e3 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -357,17 +357,22 @@ def test_incomplete_baseline_prevents_candidate_search(campaign): def test_baseline_comparison_quality_and_pause_resume(campaign): config = settings() config["quality"].pop("threshold") - config["quality"].update(mode="baseline_comparison", tolerance=0) + config["quality"].update(mode="baseline_comparison", direction="minimize", unit="%", + tolerance=0.5) config["stagnation"] = {"rounds": 1, "action": "pause"} campaign["config"].write_text(json.dumps(config)) + commit(campaign["repo"], quality=0.5, score_unit="%") begin(campaign) - result = submit(campaign, version="worse-quality", a=90, quality=0) + result = submit(campaign, version="worse-quality", a=90, quality=0.02, score_unit="fraction") assert result["state"] == "paused" assert result["latest_observation"]["assessment"]["quality_passed"] is False resumed = call(campaign, "resume", "--reason", "Reviewed system-wide bottlenecks") repeated = call(campaign, "resume", "--reason", "Reviewed system-wide bottlenecks") assert resumed["stagnation"] == repeated["stagnation"] assert resumed["state"] == "active" + accepted = submit(campaign, version="improved", a=90, quality=0.005, score_unit="fraction") + assert accepted["latest_observation"]["assessment"]["verdict"] == "PASS" + assert accepted["latest_observation"]["execution"]["quality_score"] == 0.5 def test_accepted_but_unselected_candidate_keeps_its_verdict(campaign): @@ -659,6 +664,7 @@ def test_existing_quality_reference_is_reused_only_when_compatible(campaign, com "run_id": "previous-run", "dataset": "synthetic", "scorer": "exact-v1" if compatible else "incompatible-scorer", + "unit": "points", "samples": 2, "quality": 1, } @@ -687,7 +693,7 @@ def test_reference_refresh_uses_baseline_cache_without_testing_parent_quality( reference = { "status": "completed", "revision": revision, "conditions": config["conditions"], "service_id": "previous-service", "run_id": "previous-run", - "dataset": "synthetic", "scorer": "exact-v1", "samples": 2, "quality": 1, + "dataset": "synthetic", "scorer": "exact-v1", "unit": "points", "samples": 2, "quality": 1, } protocol = Path(campaign["start"][campaign["start"].index("--protocol") + 1]) (protocol / "reference.json").write_text(json.dumps(reference)) @@ -1674,3 +1680,55 @@ def test_service_planning_brief_marks_quality_inputs_provisional(campaign): assert prepared["task_brief"]["id"] != brief["id"] assert "quality >= baseline quality - 0.1 points" in prepared["task_brief"]["quality_gate"] assert not campaign["root"].exists() + + +@pytest.mark.parametrize(("mode", "baseline", "limit", "score", "unit", "verdict"), [ + ("absolute", 0.5, 1, 0.02, "fraction", "FAIL"), + ("absolute", 0.5, 1, 0.005, "fraction", "PASS"), + ("absolute", 0.5, 1, 0.005, None, "INCONCLUSIVE"), + ("absolute", 0.5, 1, 0.005, "tokens", "INCONCLUSIVE"), + ("baseline_comparison", 2, 1, 0.03, "fraction", "PASS"), + ("baseline_comparison", 2, 1, 0.0301, "fraction", "FAIL"), +]) +def test_service_scores_in_the_approved_quality_unit(campaign, mode, baseline, limit, + score, unit, verdict): + from inferrsi.apps.cli import task_intake + from tests.fixtures.campaign_intake import approved_start + + config = settings() + quality = config["quality"] + quality.pop("threshold") + quality.update(mode=mode, direction="minimize", unit="%") + quality["tolerance" if mode == "baseline_comparison" else "threshold"] = limit + campaign["config"].write_text(json.dumps(config)) + args = approved_start(campaign["start"]) + gate, _ = task_intake.campaign_gate(Path(args[-1])) + assert gate["task_brief"]["campaign_launch"]["evaluation_settings"]["quality"]["unit"] == "%" + if mode == "baseline_comparison": + assert "1 percentage point " in gate["task_brief"]["quality_gate"] + changed = copy.deepcopy(config) + changed["quality"]["unit"] = "fraction" + campaign["config"].write_text(json.dumps(changed)) + assert main(args) == 2 + blocked = json.loads(campaign["capsys"].readouterr().out) + assert blocked["reason"] == "launch_conflict" + assert blocked["conflicts"] == [ + {"field": "protocol.quality_unit", "approved": "%", "actual": "fraction"}] + campaign["config"].write_text(json.dumps(config)) + assert main(args) == 0 + campaign["capsys"].readouterr() + frozen = project_service.read(campaign["root"] / "plan.json")["evaluation_settings"] + receipt = {"dataset": "synthetic", "scorer": "exact-v1", "samples": 2, + "quality": baseline, "unit": "%"} + reference = project_service.quality_score(frozen, receipt) + receipt["quality"] = score + if unit is None: + del receipt["unit"] + else: + receipt["unit"] = unit + if verdict == "INCONCLUSIVE": + with pytest.raises(ValueError, match="quality_unit_mismatch"): + project_service.quality_score(frozen, receipt) + else: + normalized = project_service.quality_score(frozen, receipt) + assert project_service.quality_passed(frozen, normalized, reference) is (verdict == "PASS") diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index 4a9776b40..f4b3f43cf 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -774,7 +774,7 @@ def test_boolean_quality_success_does_not_override_numeric_limit(project, capsys (project[1] / "quality.py").write_text( "import json, sys\nfrom pathlib import Path\n" "value = json.loads((Path(sys.argv[1])/'config.json').read_text())['metric']\n" - "result = {'correct':True,'errors':value-10,'dataset':'fixture-exact-v1'}\n" + "result = {'correct':True,'errors':value-10,'unit':'tokens','dataset':'fixture-exact-v1'}\n" "Path(sys.argv[2]).write_text(json.dumps(result))\n") args = approved_start(start_arguments(project), overrides={ "protocol.quality_metric": "errors", "protocol.quality_limit": 0, @@ -795,7 +795,7 @@ def test_abba_quality_rejects_foreign_or_missing_corpus(project, capsys, reporte (project[1] / "quality.py").write_text( "import json, sys\nfrom pathlib import Path\n" - "result = {'correct':True,'accuracy':100,'dataset':'fixture-exact-v1'}\n" + "result = {'correct':True,'accuracy':100,'unit':'points','dataset':'fixture-exact-v1'}\n" "if Path(sys.argv[1]).name == 'candidate':\n" f" result['dataset'] = {reported!r}\n" " if result['dataset'] is None: del result['dataset']\n" @@ -814,3 +814,37 @@ def test_abba_quality_rejects_foreign_or_missing_corpus(project, capsys, reporte assert code == 2 and result["best"]["kind"] == "baseline" assert (assessment["verdict"], assessment["reason"]) == ( "INCONCLUSIVE", "quality_benchmark_mismatch") + + +@pytest.mark.parametrize(("score", "unit", "verdict"), [ + (0.02, "fraction", "FAIL"), (0.005, "fraction", "PASS"), + (0.005, None, "INCONCLUSIVE"), (0.005, "tokens", "INCONCLUSIVE"), +]) +def test_abba_scores_in_the_approved_quality_unit(project, capsys, score, unit, verdict): # noqa: F811 + from tests.apps.test_project_optimization import submit + from tests.fixtures.diagnosis import diagnosis_args + + (project[1] / "quality.py").write_text( + "import json, sys\nfrom pathlib import Path\n" + "candidate = Path(sys.argv[1]).name == 'candidate'\n" + "result = {'correct': True, 'dataset': 'fixture-exact-v1', 'errors': 0.5, 'unit': '%'}\n" + f"if candidate: result.update(errors={score!r}, unit={unit!r})\n" + "if result['unit'] is None: del result['unit']\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n") + args = approved_start(start_arguments(project), overrides={ + "protocol.quality_metric": "errors", "protocol.quality_limit": 1, + "protocol.quality_comparator": "at_most", "protocol.quality_unit": "%"}) + assert cli.main(args) == 0 + capsys.readouterr() + frozen = json.loads((project[3] / "plan.json").read_bytes())["evaluation_settings"] + gate, _ = task_intake.campaign_gate(Path(args[-1])) + approved = gate["task_brief"]["campaign_launch"]["evaluation_settings"]["quality_bound"] + assert approved == frozen["quality_bound"] + assert approved == {"metric": "errors", "limit": 1, "comparator": "at_most", "unit": "%"} + assert cli.main(diagnosis_args(project[3], "campaign")) == 0 + capsys.readouterr() + _, result = submit(project, capsys, 20) + assessment = result["latest_observation"]["assessment"] + assert assessment["verdict"] == verdict + if verdict == "INCONCLUSIVE": + assert assessment["reason"] == "quality_unit_mismatch" diff --git a/tests/fixtures/campaign_intake.py b/tests/fixtures/campaign_intake.py index d5d0aa01f..ff4b41ef6 100644 --- a/tests/fixtures/campaign_intake.py +++ b/tests/fixtures/campaign_intake.py @@ -46,6 +46,7 @@ def approved_start(arguments, *, overrides=None): else obj["domain"]["min"], "protocol.quality_benchmark": q["dataset"], "protocol.quality_metric": q["key"], + "protocol.quality_unit": q["unit"], "protocol.quality_comparator": cmp, "protocol.quality_limit": q["tolerance" if relative else "threshold"], "protocol.service_lifecycle": "fixture owned process", diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index c2ea5b910..eaf6ffc62 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -122,6 +122,7 @@ def settings(): "mode": "absolute", "dataset": "synthetic", "scorer": "exact-v1", + "unit": "points", "samples": 2, "key": "quality", "direction": "maximize", diff --git a/tests/fixtures/service_reuse_protocol.py b/tests/fixtures/service_reuse_protocol.py index 35dc4a1d5..117c2f20a 100644 --- a/tests/fixtures/service_reuse_protocol.py +++ b/tests/fixtures/service_reuse_protocol.py @@ -68,6 +68,7 @@ def do_GET(self): body.update( dataset="synthetic", scorer="exact-v1", + unit=config.get("score_unit", "points"), samples=2, quality=config.get("quality", 1), ) diff --git a/tests/harness/test_service_reference_evidence.py b/tests/harness/test_service_reference_evidence.py index 1f1e1fbfc..9f70fb78a 100644 --- a/tests/harness/test_service_reference_evidence.py +++ b/tests/harness/test_service_reference_evidence.py @@ -115,6 +115,7 @@ def test_changed_external_baseline_quality_reference_blocks_final(campaign): "run_id": "external-run", "dataset": "synthetic", "scorer": "exact-v1", + "unit": "points", "samples": 2, "quality": 1, } From a8b619985bbb86fe16906c071e3ced83eec85b93 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 20:05:16 +0800 Subject: [PATCH 20/26] Bind each field reply to the card and context that issued it Keep unaffected batch tokens across edits, reissue changed choices and reject late or legacy open tokens before writing. Preserve provenance for existing settled answers. Exercise the reviewed percent and fraction cases through independent final evaluation. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: jiangkuaixue123 --- docs/guides/task-intake.md | 10 ++- src/inferrsi/apps/cli/intake_contract.py | 50 +++++------ src/inferrsi/apps/cli/task_intake.py | 4 +- tests/apps/test_project_service_reuse.py | 10 ++- tests/apps/test_task_intake.py | 107 ++++++++++++++++++++--- 5 files changed, 138 insertions(+), 43 deletions(-) diff --git a/docs/guides/task-intake.md b/docs/guides/task-intake.md index 91a814343..780c49aaf 100644 --- a/docs/guides/task-intake.md +++ b/docs/guides/task-intake.md @@ -37,7 +37,7 @@ If an update is in progress, retry after it finishes. "acceptance.reference": {"value": "", "source": "prompt", "status": "confirmed"}, "acceptance.metric_key": {"value": "p95_ttft", "source": "issue", "status": "confirmed", "authority_reference": ""}, - "protocol.comparison": {"value": null, "source": "answer:q:protocol.comparison", + "protocol.comparison": {"value": null, "source": "answer:q:protocol.comparison:", "status": "unknown", "asked": true} }, "open_questions": [], @@ -108,7 +108,11 @@ blocks candidate search. batches wait until earlier batches settle. 4. `unknown` is a recorded answer: the field is not asked again, and it blocks every stage named in `required_before`. -5. Each question carries a dependency snapshot. An answer is rejected as +5. Reply with the full ID returned on the displayed card. Its token binds the + record, field, dependencies and options at issuance. Re-evaluation keeps the + IDs of open, unchanged questions. A changed or reopened card receives a new + token. For a legacy field-only card, re-evaluate and present its new ID. + An answer is rejected as `stale_answer` when the snapshot changed, as `already_answered` when the same question was answered once, and as `unknown_question` when it was never issued. A late reply to a superseded question changes nothing. @@ -127,7 +131,7 @@ For an issue, first record the user's reference, then include the same user's selection. For example, after the user chooses the file on a card: ```text -inferrsi task intake answer --record --question q:acceptance.reference \ +inferrsi task intake answer --record --question \ --value --frozen ``` diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index ce0c68687..d3ce2f075 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -182,6 +182,8 @@ def bad(field: str, message: str) -> None: revision = record.get("revision") if type(revision) is not int or revision < 1: bad("revision", "must be a positive integer") + if not isinstance(record.get("open_questions", []), list): + bad("open_questions", "must be a list of issued questions") primary = record.get("primary_task") if not isinstance(primary, dict) or primary.get("status") not in STATUSES: bad("primary_task", "must carry a value, source and known status") @@ -277,8 +279,13 @@ def _coerce(field: dict, value: object) -> object: return typed +def _card_source(path: str, source: str) -> bool: + # Older settled answers retain their field-only provenance. + return source.split(":", 3)[:3] == ["answer", "q", path] + + def _user_source(path: str, source: str) -> bool: - return source in ("prompt", "grilling_brief") or source == f"answer:{_QUESTION}{path}" + return source in ("prompt", "grilling_brief") or _card_source(path, source) def selected_reference(record: dict) -> str | None: @@ -422,7 +429,7 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: continue if (current is not None and current.get("status") not in (None, "unknown") and current.get("value") is not None and current.get("value") != value): - disagrees_with_answer = bound and current.get("source") == f"answer:{_QUESTION}{path}" + disagrees_with_answer = bound and _card_source(path, current["source"]) if _rank(status) > _rank(current["status"]) and not disagrees_with_answer: updated["fields"][path] = entry changed = True @@ -447,21 +454,6 @@ def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: return updated -def set_primary_task(record: dict, spec: dict, *, value: str, source: str) -> dict: - """Change the selected primary task; open questions become stale by snapshot.""" - _check(record, spec) - if value != record["task"]: - raise IntakeError( - "invalid_primary_task", - f"record task is {record['task']}; a different primary task needs its own record", - ) - updated = copy.deepcopy(record) - if updated["primary_task"].get("source") != source: - updated["primary_task"] = {"value": value, "source": source, "status": "confirmed"} - _bump(updated, updated["revision"] + 1) - return updated - - def _applicable(record: dict, field: dict) -> bool: for dep in field.get("depends_on", []): if not _settled(record, dep): @@ -474,7 +466,7 @@ def _applicable(record: dict, field: dict) -> bool: return True -def _question(record: dict, spec: dict, field: dict) -> dict: +def _question(record: dict, field: dict) -> dict: snapshot = {"__primary_task__": record["primary_task"]["value"]} dependencies = list(field.get("depends_on", [])) when = field.get("required_when") @@ -491,8 +483,7 @@ def _question(record: dict, spec: dict, field: dict) -> dict: if entry.get("status") == "conflicting" and isinstance(entry.get("candidates"), list): options = [{"value": item["value"], "hint": f"from {item['source']}"} for item in entry["candidates"]] - return { - "id": _QUESTION + field["path"], + card = { "field": field["path"], "batch": field.get("batch", 1), "question": field["question"], @@ -500,6 +491,16 @@ def _question(record: dict, spec: dict, field: dict) -> dict: "fallback": "unknown", "depends_on": snapshot, } + # Keep a batch sibling's token across unrelated edits. A reissued card gets + # the new revision even if a previous set of choices eventually comes back. + issued = record["revision"] + for prior in record.get("open_questions", []): + if isinstance(prior, dict) and all(prior.get(key) == value for key, value in card.items()): + issued = prior.get("issued_revision", issued) + break + identity = _canonical([record["record_id"], issued, card]) + digest = hashlib.sha256(identity.encode()).hexdigest() + return {**card, "id": f"{_QUESTION}{field['path']}:{digest}", "issued_revision": issued} def _frozen_conflicts(record: dict, spec: dict, frozen: dict | None) -> list[dict]: @@ -619,7 +620,7 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: if missing: lowest = min(field.get("batch", 1) for field in missing) question_fields = [field for field in missing if field.get("batch", 1) == lowest] - questions = [_question(record, spec, field) for field in question_fields] + questions = [_question(record, field) for field in question_fields] blockers = [] for stage in BLOCKING_STAGES: blocked_by = [] @@ -719,8 +720,8 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, raise IntakeError("already_answered", f"{question_id} was already recorded; re-evaluate for " "current questions") - named = question_id[len(_QUESTION):] if question_id.startswith(_QUESTION) else None - if named in _field_paths(spec): + prefix, separator, remainder = question_id.partition(":") + if prefix + separator == _QUESTION and remainder.partition(":")[0] in _field_paths(spec): raise IntakeError("stale_answer", f"{question_id} is not open in the current record; re-evaluate") raise IntakeError("unknown_question", @@ -742,8 +743,7 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, if field is None: raise IntakeError("unknown_question", f"{question_id} names a field outside {spec['task']}; re-evaluate") - snapshot = _question(record, spec, field)["depends_on"] - if snapshot != question.get("depends_on"): + if _question(record, field)["id"] != question_id: raise IntakeError("stale_answer", f"{question_id} was asked before its dependencies changed; " "re-evaluate") diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 1ee0ba447..394363375 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -196,8 +196,8 @@ def answer_command(args) -> dict: spec = load_spec(record["task"]) record = intake.answer(record, spec, question_id=args.question, value=args.value, unknown=bool(args.unknown)) - return _evaluate_and_save(record_path, record, spec, args.frozen, - selecting_reference=args.question == f"q:{intake.REFERENCE}") + selected = record["fields"].get(intake.REFERENCE, {}).get("source") == f"answer:{args.question}" + return _evaluate_and_save(record_path, record, spec, args.frozen, selecting_reference=selected) def summary_command(args) -> dict: diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 649c057e3..8f29964cc 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -70,8 +70,16 @@ def events(campaign, attempt): def test_one_service_order_and_independent_final_ignores_workspace(campaign): + config = settings() + config["quality"].update(direction="minimize", unit="%", threshold=1) + campaign["config"].write_text(json.dumps(config)) + commit(campaign["repo"], quality=0.005, score_unit="fraction") begin(campaign) - result = submit(campaign, version="accepted", a=95, b=102) + failed = submit(campaign, version="wrong-quality", a=90, quality=0.02, score_unit="fraction") + assert failed["latest_observation"]["assessment"]["verdict"] == "FAIL" + assert failed["best"]["kind"] == "baseline" + result = submit(campaign, version="accepted", a=95, b=102, quality=0.005, + score_unit="fraction") attempt = result["latest_observation"] assert attempt["assessment"]["verdict"] == "PASS" log = events(campaign, attempt) diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index f4b3f43cf..5fe29b428 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -52,6 +52,10 @@ def ask(record: dict, spec: dict, frozen: dict | None = None) -> tuple[dict, dic return record, view +def card_id(record, field): + return next(q["id"] for q in record["open_questions"] if q["field"] == field) + + def batch_paths(spec: dict, batch: int) -> set[str]: return {field["path"] for field in spec["fields"] if field.get("batch", 1) == batch} @@ -217,7 +221,7 @@ def call(*args): assert {opt["value"] for opt in card["options"]} == {"p95_ttft", "p99_ttft"} assert call("evaluate", "--set", f"{metric}={selected}")["revision"] == view["revision"] chosen = call("answer", "--question", card["id"], "--value", selected) - assert chosen["fields"][metric] == {"value": selected, "source": f"answer:q:{metric}", + assert chosen["fields"][metric] == {"value": selected, "source": "answer:" + card["id"], "status": "proposed"} assert not any(q["field"] == metric for q in chosen["questions"]) issue = call("evaluate", "--source", "issue", "--set", f"{metric}={selected}", @@ -231,7 +235,7 @@ def test_mismatching_issue_reopens_an_explicit_card_choice(): record = build({intake.REFERENCE}) record, _ = ask(record, spec) key = "acceptance.metric_key" - record = intake.answer(record, spec, question_id=f"q:{key}", value="p95_ttft") + record = intake.answer(record, spec, question_id=card_id(record, key), value="p95_ttft") record = intake.set_fields(record, spec, {key: "p99_ttft", intake.REFERENCE: ALL_VALUES[intake.REFERENCE]}, source="issue") view = intake.evaluate(record, spec) @@ -481,13 +485,13 @@ def test_selected_gate_imports_only_its_values_and_changed_file_reopens_card(tmp cmd = ["task", "intake", "evaluate", "--record", str(record), "--json"] assert cli.main([*cmd, "--task", "task-performance"]) == 0 capsys.readouterr() - + reference_card = card_id(task_intake.read_record(record), intake.REFERENCE) answer = ["task", "intake", "answer", "--record", str(record), "--question", - "q:acceptance.reference", "--value", str(gate), "--frozen", str(gate), "--json"] + reference_card, "--value", str(gate), "--frozen", str(gate), "--json"] assert cli.main(answer) == 0 view = json.loads(capsys.readouterr().out) assert view["fields"]["acceptance.metric_key"]["status"] == "confirmed" - assert view["fields"][intake.REFERENCE]["source"] == "answer:q:acceptance.reference" + assert view["fields"][intake.REFERENCE]["source"] == "answer:" + reference_card assert cli.main([*cmd, "--source", "frozen_gate", "--set", "acceptance.min_improvement_pct=99"]) == 0 assert json.loads(capsys.readouterr().out)["fields"]["acceptance.min_improvement_pct"][ @@ -526,13 +530,15 @@ def test_user_can_replace_suggested_goal_and_settle_a_conflict(): record = intake.set_fields(record, spec, {"optimization.objective": "throughput"}, source="repo_inspection") record, _ = ask(record, spec) - record = intake.answer(record, spec, question_id="q:optimization.objective", value="latency") + record = intake.answer(record, spec, question_id=card_id(record, "optimization.objective"), + value="latency") assert record["fields"]["optimization.objective"]["value"] == "latency" assert record["fields"]["optimization.objective"]["status"] == "confirmed" record = intake.set_fields(record, spec, {"optimization.objective": "memory"}, source="prompt") record, view = ask(record, spec) assert view["questions"][0]["field"] == "optimization.objective" - record = intake.answer(record, spec, question_id="q:optimization.objective", value="latency") + record = intake.answer(record, spec, question_id=card_id(record, "optimization.objective"), + value="latency") assert record["fields"]["optimization.objective"]["status"] == "confirmed" @pytest.mark.parametrize("path", ["protocol.target_value", "protocol.quality_limit", @@ -562,7 +568,7 @@ def test_brief_answer_must_match_the_current_issued_revision(): with pytest.raises(intake.IntakeError): intake.answer(changed, spec, question_id=review, value="approve") changed, _ = ask(changed, spec) - changed = intake.answer(changed, spec, question_id="q:protocol.target_kind", + changed = intake.answer(changed, spec, question_id=card_id(changed, "protocol.target_kind"), value="relative_improvement_pct") changed, next_view = ask(changed, spec) assert "12%" in next_view["task_brief"]["performance_target"] @@ -584,7 +590,8 @@ def test_returned_brief_waits_for_edits_then_requires_new_review(reply): intake.answer(record, spec, question_id=view["task_brief"]["id"], value="approve") edited = intake.set_fields(record, spec, {"protocol.quality_limit": 2}, source="prompt") edited, _ = ask(edited, spec) - edited = intake.answer(edited, spec, question_id="q:protocol.quality_limit", value=2) + edited = intake.answer(edited, spec, question_id=card_id(edited, "protocol.quality_limit"), + value=2) assert intake.evaluate(edited, spec)["brief_review"] == "awaiting_confirmation" @@ -696,8 +703,9 @@ def test_loaded_approved_record_reopens_unusable_execution_values(project, tmp_p assert "brief_decision" not in json.loads(path.read_text()) assert reopened["revision"] > record["revision"] for key in ("environment.repetitions", "environment.max_minutes", "environment.rounds"): + token = card_id(task_intake.read_record(path), key) assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", - "--question", f"q:{key}", "--value", "1"]) == 0 + "--question", token, "--value", "1"]) == 0 view = json.loads(capsys.readouterr().out) assert view["brief_review"] == "awaiting_confirmation" assert not view["complete"] @@ -846,5 +854,80 @@ def test_abba_scores_in_the_approved_quality_unit(project, capsys, score, unit, _, result = submit(project, capsys, 20) assessment = result["latest_observation"]["assessment"] assert assessment["verdict"] == verdict - if verdict == "INCONCLUSIVE": - assert assessment["reason"] == "quality_unit_mismatch" + if verdict == "PASS": + assert cli.main(["campaign", "final", "--directory", str(project[3]), + "--reason", "independent retest"]) == 0 + capsys.readouterr() + final = json.loads((project[3] / "state.json").read_bytes())["final"]["assessment"] + assert final["verdict"] == "PASS" + else: + assert result["best"]["kind"] == "baseline" + if verdict == "INCONCLUSIVE": + assert assessment["reason"] == "quality_unit_mismatch" + + +def test_reissued_field_rejects_delayed_reply_and_keeps_unaffected_sibling(tmp_path, capsys): + path = tmp_path / "intake.json" + base = ["task", "intake"] + record = ["--record", str(path), "--json"] + metric = "acceptance.metric_key" + gain = "acceptance.min_improvement_pct" + sibling = "protocol.timing_boundary" + assert cli.main([*base, "evaluate", *record, "--task", "task-performance", + "--set", "acceptance.reference=fixture", "--set", f"{metric}=p95"]) == 0 + capsys.readouterr() + original = task_intake.read_record(path) + assert cli.main([*base, "evaluate", *record, "--source", "issue", + "--set", "acceptance.reference=fixture", "--set", f"{metric}=p99"]) == 0 + capsys.readouterr() + current = task_intake.read_record(path) + assert card_id(original, gain) != card_id(current, gain) + assert card_id(original, sibling) == card_id(current, sibling) + before = path.read_bytes() + for stale in (card_id(original, gain), f"q:{gain}"): + assert cli.main([*base, "answer", *record, "--question", stale, "--value", "5"]) == 2 + assert json.loads(capsys.readouterr().out)["error"] == "stale_answer" + assert path.read_bytes() == before + assert cli.main([*base, "answer", *record, "--question", card_id(original, sibling), + "--value", "end-to-end"]) == 0 + capsys.readouterr() + assert cli.main([*base, "answer", *record, "--question", card_id(current, gain), + "--value", "5"]) == 0 + assert json.loads(capsys.readouterr().out)["fields"][gain]["value"] == 5 + + +def test_issued_field_token_binds_record_and_conflict_options(): + spec = spec_for() + key = "optimization.objective" + record = intake.new_record("task-performance", record_id="first") + for value in ("throughput", "latency"): + record = intake.set_fields(record, spec, {key: value}, source="prompt") + record, _ = ask(record, spec) + original = card_id(record, key) + for updated in ({**record, "record_id": "second"}, + intake.set_fields(record, spec, {key: "memory"}, source="prompt")): + updated, _ = ask(updated, spec) + assert card_id(updated, key) != original + with pytest.raises(intake.IntakeError) as rejected: + intake.answer(updated, spec, question_id=original, value="latency") + assert rejected.value.code == "stale_answer" + chosen = intake.answer(updated, spec, question_id=card_id(updated, key), value="latency") + assert chosen["fields"][key]["status"] == "confirmed" + + +def test_legacy_open_token_must_be_reissued_but_settled_answers_keep_provenance(): + spec = spec_for() + key = "optimization.objective" + record, _ = ask(build({intake.REFERENCE}), spec) + reference = record["fields"][intake.REFERENCE] + reference["source"] = f"answer:q:{intake.REFERENCE}" + for card in record["open_questions"]: + card["id"] = "q:" + card["field"] + card.pop("issued_revision") + with pytest.raises(intake.IntakeError) as rejected: + intake.answer(record, spec, question_id="q:" + key, value="latency") + assert rejected.value.code == "stale_answer" + assert intake.selected_reference(record) == reference["value"] + record, _ = ask(record, spec) + reply = intake.answer(record, spec, question_id=card_id(record, key), value="latency") + assert reply["fields"][key]["status"] == "confirmed" From e976c1d18724612c156626b5fc0897c0f534c2bf Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 20:33:57 +0800 Subject: [PATCH 21/26] Cover packaged execution-bound mapping and per-field saved-record reopening Assert that environment.repetitions, rounds and max_minutes map to the task-input/v1 count/minutes bounds, and that a saved record holding 0, -1 or -5 reopens that field and rejects the same value again on answer. Co-Authored-By: Claude Opus 5.5 --- tests/apps/test_task_intake.py | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index 5fe29b428..fe7cd3dd4 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -655,6 +655,18 @@ def test_user_can_choose_a_different_gate_after_returning_the_brief(tmp_path, ca assert updated["brief_review"] == "awaiting_confirmation" assert updated["task_brief"]["id"] != view["task_brief"]["id"] +def test_packaged_execution_fields_use_task_input_bounds(): + from inferrsi.apps.cli import task_input + fields = {field["path"]: field for field in spec_for()["fields"]} + expected = {"environment.repetitions": ("integer", "count"), + "environment.rounds": ("integer", "count"), + "environment.max_minutes": ("number", "minutes")} + for path, (kind, bound) in expected.items(): + assert fields[path]["maps_to"] == "task-input/v1" + assert fields[path]["type"] == kind + assert task_input.BY_PATH[path].kind == bound + + @pytest.mark.parametrize(("key", "invalid", "valid"), [ ("environment.repetitions", 0, 1), ("environment.rounds", -1, 1), @@ -711,6 +723,31 @@ def test_loaded_approved_record_reopens_unusable_execution_values(project, tmp_p assert not view["complete"] +@pytest.mark.parametrize(("key", "invalid"), [ + ("environment.repetitions", 0), + ("environment.rounds", -1), + ("environment.max_minutes", -5), +]) +def test_saved_record_reopens_one_unusable_value_and_rejects_it_again(tmp_path, capsys, key, + invalid): + path = tmp_path / "intake.json" + record = approved_record() + record["fields"][key]["value"] = invalid + record["complete"] = True + path.write_text(json.dumps(record)) + assert cli.main(["task", "intake", "evaluate", "--record", str(path), "--json"]) == 0 + reopened = json.loads(capsys.readouterr().out) + assert reopened["fields"][key]["status"] == "unknown" + assert not reopened["complete"] + token = card_id(task_intake.read_record(path), key) + unchanged = path.read_bytes() + assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", + "--question", token, "--value", str(invalid)]) == 2 + error = json.loads(capsys.readouterr().out) + assert error["error"] == "invalid_value" and key in error["message"] + assert path.read_bytes() == unchanged + + @pytest.mark.parametrize(("flag", "value", "reason"), [ ("--metric-unit", "other", "launch_conflict"), ("--measure-command", "{python} {protocol}/different.py {result}", "launch_conflict"), From abe02d322ad61360f354dcf192182aa04a3a8f4d Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 21:21:52 +0800 Subject: [PATCH 22/26] Reject placeholder quality units at intake and service-reuse start Share the scoring rule for unspecified quality units (empty, unknown, unspecified, n/a) with intake coercion and service-reuse validation, so a placeholder unit can no longer be set, approved or frozen into a plan. A saved record holding one reopens the field for a real answer. Cover unknown -> % re-approval through a scored 0.005 fraction PASS, and the service-reuse pre-start rejection. Co-Authored-By: Claude Opus 5.5 --- src/inferrsi/apps/cli/intake_contract.py | 5 +- src/inferrsi/harness/project.py | 13 ++++-- src/inferrsi/harness/project_service.py | 3 +- tests/apps/test_project_service_reuse.py | 9 ++++ tests/apps/test_task_intake.py | 58 ++++++++++++++++++++++++ 5 files changed, 82 insertions(+), 6 deletions(-) diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index d3ce2f075..05ed50bd5 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -19,6 +19,7 @@ import json import math +from ...harness.project import quality_unit_declared from . import task_input SCHEMA_VERSION = 1 @@ -276,6 +277,8 @@ def _coerce(field: dict, value: object) -> object: problem = task_input.field_value_problem(mapped, typed) if problem: raise IntakeError("invalid_value", f"{mapped.path} {problem}") + if field["path"] == "protocol.quality_unit" and not quality_unit_declared(typed): + raise IntakeError("invalid_value", f"{field['path']} must name a unit, not {typed!r}") return typed @@ -348,7 +351,7 @@ def reconcile_record(record: dict, spec: dict) -> dict: for path, entry in updated["fields"].items(): if entry["status"] in ("confirmed", "proposed", "assumed"): field = fields[path] - if field.get("type") in ("integer", "number"): + if field.get("type") in ("integer", "number") or path == "protocol.quality_unit": try: _coerce(field, entry.get("value")) except IntakeError: diff --git a/src/inferrsi/harness/project.py b/src/inferrsi/harness/project.py index ca7881199..1c1c16e8f 100644 --- a/src/inferrsi/harness/project.py +++ b/src/inferrsi/harness/project.py @@ -116,12 +116,17 @@ def meets_target(target, *, baseline, candidate, direction): return (change if direction == "maximize" else -change) >= target["target_value"] +UNSPECIFIED_QUALITY_UNITS = ("", "unknown", "unspecified", "n/a") + + +def quality_unit_declared(unit) -> bool: + return isinstance(unit, str) and unit.strip().lower() not in UNSPECIFIED_QUALITY_UNITS + + def quality_score_in_unit(score, reported_unit, approved_unit): """Return the score in the frozen unit; only proportional scales can cross units.""" - unspecified = ("", "unknown", "unspecified", "n/a") - for unit in (reported_unit, approved_unit): - if not isinstance(unit, str) or unit.strip().lower() in unspecified: - raise ValueError("quality_unit_mismatch") + if not (quality_unit_declared(reported_unit) and quality_unit_declared(approved_unit)): + raise ValueError("quality_unit_mismatch") if reported_unit == approved_unit: return score scales = {"%": 2, "percent": 2, "fraction": 0, "ratio": 0} diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index 0092342ea..ece1640e3 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -17,7 +17,7 @@ from .atomic_json import atomic_write_json from .candidates import members, retain -from .project import meets_target, quality_score_in_unit +from .project import meets_target, quality_score_in_unit, quality_unit_declared INLINE_PROFILE_REASONS = ("fixed_checks_satisfied", "performance_gate_not_met") @@ -204,6 +204,7 @@ def validate(settings): isinstance(quality.get(key), str) and quality[key].strip() for key in ("key", "dataset", "scorer", "unit") ) + or not quality_unit_declared(quality["unit"]) ): raise ValueError("Declare quality mode, direction, dataset, scorer, unit and key") gate = "threshold" if quality["mode"] == "absolute" else "tolerance" diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 8f29964cc..23aa42f2d 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -632,6 +632,15 @@ def test_invalid_protocol_containers_rejected_before_campaign_writes(campaign, b assert not campaign["root"].exists() +@pytest.mark.parametrize("unit", ["unknown", " N/A ", "unspecified"]) +def test_placeholder_quality_unit_rejected_before_campaign_writes(campaign, unit): + config = settings() + config["quality"]["unit"] = unit + campaign["config"].write_text(json.dumps(config)) + assert rejected(campaign["start"]) == 2 + assert not campaign["root"].exists() + + def test_live_dashboard_state_has_no_content_fingerprint(campaign): import threading from urllib.request import urlopen diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py index fe7cd3dd4..06eb8fa46 100644 --- a/tests/apps/test_task_intake.py +++ b/tests/apps/test_task_intake.py @@ -903,6 +903,64 @@ def test_abba_scores_in_the_approved_quality_unit(project, capsys, score, unit, assert assessment["reason"] == "quality_unit_mismatch" +def test_placeholder_quality_unit_is_never_approved_or_started(project, tmp_path, capsys): # noqa: F811 + from tests.apps.test_project_optimization import submit + from tests.fixtures.diagnosis import diagnosis_args + + key = "protocol.quality_unit" + open_path = tmp_path / "open.json" + open_path.write_text(json.dumps(build(set(ALL_VALUES) - {key}))) + record = ["--record", str(open_path), "--json"] + assert cli.main(["task", "intake", "evaluate", *record]) == 0 + token = next(q["id"] for q in json.loads(capsys.readouterr().out)["questions"] + if q["field"] == key) + unchanged = open_path.read_bytes() + for cmd in (["evaluate", "--set", f"{key}=unknown"], + ["answer", "--question", token, "--value", "unknown"], + ["answer", "--question", token, "--value", "N/A"]): + assert cli.main(["task", "intake", *cmd, *record]) == 2 + error = json.loads(capsys.readouterr().out) + assert error["error"] == "invalid_value" and key in error["message"] + assert open_path.read_bytes() == unchanged + + (project[1] / "quality.py").write_text( + "import json, sys\nfrom pathlib import Path\n" + "candidate = Path(sys.argv[1]).name == 'candidate'\n" + "result = {'correct': True, 'dataset': 'fixture-exact-v1', 'errors': 0.5, 'unit': '%'}\n" + "if candidate: result.update(errors=0.005, unit='fraction')\n" + "Path(sys.argv[2]).write_text(json.dumps(result))\n") + args = approved_start(start_arguments(project), overrides={ + "protocol.quality_metric": "errors", "protocol.quality_limit": 1, + "protocol.quality_comparator": "at_most", key: "%"}) + path = Path(args[-1]) + imported = json.loads(path.read_text()) + imported["fields"][key]["value"] = "unknown" + path.write_text(json.dumps(imported)) + assert cli.main(args) == 2 + assert json.loads(capsys.readouterr().out)["status"] == "blocked" + assert not project[3].exists() + assert cli.main(["task", "intake", "evaluate", "--record", str(path), "--json"]) == 0 + view = json.loads(capsys.readouterr().out) + assert view["fields"][key]["status"] == "unknown" and not view["complete"] + + token = card_id(task_intake.read_record(path), key) + assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", + "--question", token, "--value", "%"]) == 0 + capsys.readouterr() + assert cli.main([*args, "--prepare-intake"]) == 0 + brief = json.loads(capsys.readouterr().out)["task_brief"] + assert brief["conditions"][key] == "%" + assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", + "--question", brief["id"], "--value", "approve"]) == 0 + capsys.readouterr() + assert cli.main(args) == 0 + capsys.readouterr() + assert cli.main(diagnosis_args(project[3], "campaign")) == 0 + capsys.readouterr() + _, result = submit(project, capsys, 20) + assert result["latest_observation"]["assessment"]["verdict"] == "PASS" + + def test_reissued_field_rejects_delayed_reply_and_keeps_unaffected_sibling(tmp_path, capsys): path = tmp_path / "intake.json" base = ["task", "intake"] From 9541e1738e4109fc3e4b1b3403e1c82ebef3b36d Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Thu, 26 Nov 2026 21:28:13 +0800 Subject: [PATCH 23/26] Trim redundant intake docstrings Drop docstrings that restate the function signature and shorten the module and gate docstrings to the invariants a reader cannot see from the code: proposals never freeze a gate, unknown answers are not re-asked, late replies change nothing, and the retained record is the one the gate evaluated. Co-Authored-By: Claude Opus 5.5 --- src/inferrsi/apps/cli/__init__.py | 6 ++-- src/inferrsi/apps/cli/intake_contract.py | 36 ++++++------------------ src/inferrsi/apps/cli/task_intake.py | 14 ++------- 3 files changed, 13 insertions(+), 43 deletions(-) diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index bea5d8991..8d571fcd6 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -345,10 +345,8 @@ def _context(records: list[dict]) -> str: def _task_command(args) -> int: - """Read one task file and print to stdout; no subprocess, probe or file write. - - ``task intake evaluate`` and ``answer`` are the exception: they also write the - caller-named ``--record`` file. They start no subprocess or probe either. + """Read one task file and print to stdout; no subprocess or probe. Only + ``task intake`` writes, and only its ``--record`` file. """ from . import task_input diff --git a/src/inferrsi/apps/cli/intake_contract.py b/src/inferrsi/apps/cli/intake_contract.py index 05ed50bd5..fcb3d778e 100644 --- a/src/inferrsi/apps/cli/intake_contract.py +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -1,15 +1,7 @@ -"""intake/v1: host-independent task intake records for missing-field confirmation. - -A card, a numbered text fallback and an optional check-in interview all write the -same record. The record separates what the user stated (``confirmed``), what a -card answer proposes (``proposed``), what stays unknown (``unknown``) and what -conflicts (``conflicting``). ``evaluate`` selects the questions that unblock the -next stage, derives ``allowed_next`` and never authenticates acceptance -thresholds: a proposal kept in a record does not freeze a gate. - -The contract performs no I/O. Mapped numeric values use the task-input validator. Callers in -``inferrsi.apps.cli.task_intake`` load the versioned spec and record, then call these -pure functions. ``source`` is declared by the caller and is not authenticated. +"""intake/v1: pure functions over task intake records; no I/O. + +A proposal kept in a record never freezes an acceptance gate, and ``source`` is +declared by the caller, not authenticated. """ from __future__ import annotations @@ -141,7 +133,6 @@ def bad(path: str, message: str) -> None: def load_spec(spec: object) -> dict: - """Validate and return the spec; raise ``IntakeError('invalid_spec')``.""" problems = validate_spec(spec) if problems: first = problems[0] @@ -168,7 +159,6 @@ def new_record(task: str, *, record_id: str, primary_source: str = "prompt") -> def validate_record(record: object, spec: dict) -> list[dict]: - """Return field-level problems in a record against its spec.""" problems: list[dict] = [] def bad(field: str, message: str) -> None: @@ -389,7 +379,6 @@ def _rank(status: str) -> int: def set_fields(record: dict, spec: dict, values: dict, *, source: str) -> dict: - """Merge stated values into a copy of ``record``; raise on invalid fields/values.""" if source.startswith("answer:"): raise IntakeError("invalid_source", "Use intake answer to record a user reply") if not isinstance(values, dict): @@ -593,12 +582,8 @@ def _brief_question(brief: dict) -> dict: def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: - """Return the questions, blockers, conflicts and allowed next steps. - - Questions are the fields of the lowest missing ``batch`` that still apply; - a conflicting field is asked before anything else so the user can resolve - it. A field answered with ``unknown`` is not asked again: it blocks its - stage until a later source states it. + """Conflicts are asked first, then the lowest missing batch. A field answered + ``unknown`` is not asked again; it blocks its stage until a source states it. """ record = reconcile_record(record, spec) fields = _field_paths(spec) @@ -702,12 +687,8 @@ def evaluate(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: def answer(record: dict, spec: dict, *, question_id: str, value: object = None, unknown: bool = False) -> dict: - """Apply one answer to a copy of ``record``. - - The question must be one ``evaluate`` previously recorded in - ``record["open_questions"]``; its dependency snapshot must still hold and - the field must still be open. A duplicate, stale or inapplicable delivery - is rejected, so a late reply to a superseded question changes nothing. + """Only a question recorded by ``evaluate`` whose snapshot still holds is + accepted, so a late reply to a superseded question changes nothing. """ record = reconcile_record(record, spec) open_questions = record.get("open_questions") @@ -775,7 +756,6 @@ def answer(record: dict, spec: dict, *, question_id: str, value: object = None, def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: - """A readable confirmation summary: sources, proposals, unknowns and next steps.""" view = evaluate(record, spec, frozen=frozen) confirmed, proposed, unknown = {}, {}, [] for field in spec["fields"]: diff --git a/src/inferrsi/apps/cli/task_intake.py b/src/inferrsi/apps/cli/task_intake.py index 394363375..4d9c565b9 100644 --- a/src/inferrsi/apps/cli/task_intake.py +++ b/src/inferrsi/apps/cli/task_intake.py @@ -1,10 +1,4 @@ -"""intake/v1 CLI: evaluate, answer and summarize confirmation records. - -The contract lives in ``inferrsi.apps.cli.intake_contract``. This module loads the -versioned per-task spec and the record file, applies the pure contract -functions and writes the record back. It starts nothing and measures nothing; -``execution`` stays ``not started`` until an existing operation is authorized. -""" +"""intake/v1 CLI: load spec and record, apply ``intake_contract``, write the record back.""" from __future__ import annotations @@ -209,10 +203,8 @@ def summary_command(args) -> dict: def campaign_gate(path: Path, *, expected_task: str = "task-performance", frozen: dict | None = None) -> tuple[dict, dict]: - """Evaluate a record for ``campaign start``; return the gate and the record it read. - - Never starts or measures anything. The caller retains the returned record, so the - bytes kept next to the campaign are the ones this gate evaluated. + """Return the gate and the record it read; retain that record, so the bytes kept + next to the campaign are the ones this gate evaluated. """ record = read_record(Path(path)) if record.get("task") != expected_task: From 9799392609a9c7c7437219b5b71684ae41c2f534 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Fri, 27 Nov 2026 10:46:49 +0800 Subject: [PATCH 24/26] Apply the approved final target to a selected service baseline Skip self-gain comparison when the baseline is still selected, then apply the frozen performance target to the new final measurement. A passing target proceeds to independent quality validation. Agent-assisted-by: Codex (author) Signed-off-by: jiangkuaixue123 --- src/inferrsi/harness/evaluator/_service.py | 5 ++-- .../harness/executor/serving/_attempt.py | 6 ++--- tests/apps/test_project_service_reuse.py | 24 ++++++++++++++++--- tests/harness/test_project_objectives.py | 20 ++++++++++++++++ 4 files changed, 47 insertions(+), 8 deletions(-) diff --git a/src/inferrsi/harness/evaluator/_service.py b/src/inferrsi/harness/evaluator/_service.py index d928a2fd7..b950eb4b7 100644 --- a/src/inferrsi/harness/evaluator/_service.py +++ b/src/inferrsi/harness/evaluator/_service.py @@ -68,7 +68,8 @@ def service_metric_change(obj, candidate, reference): def assess_service_performance(settings, measured, parent, initial, *, screening=False, target=None, target_failure="performance_gate_not_met"): metrics, limits, gain, actual_gain = {}, True, False, False - for obj in settings["objectives"]: + objectives = settings["objectives"] if parent is not None else () + for obj in objectives: name = obj["id"] p = service_metric_change(obj, measured["values"][name], parent["values"][name]) b = service_metric_change(obj, measured["values"][name], initial["values"][name]) @@ -94,7 +95,7 @@ def assess_service_performance(settings, measured, parent, initial, *, screening limits &= bounded actual_gain |= improved gain |= metrics[name]["gain_passed"] - passed = limits and (actual_gain if screening else gain) + passed = parent is None or (limits and (actual_gain if screening else gain)) reason = "performance_gate_satisfied" if passed else "performance_gate_not_met" if passed and target: name = settings["ranking"][0] diff --git a/src/inferrsi/harness/executor/serving/_attempt.py b/src/inferrsi/harness/executor/serving/_attempt.py index f4069d2bc..6014c5722 100644 --- a/src/inferrsi/harness/executor/serving/_attempt.py +++ b/src/inferrsi/harness/executor/serving/_attempt.py @@ -216,10 +216,10 @@ def evaluate(role): target_failure = "final_performance_target_not_met" gate = ( evaluator.assess_service_performance( - settings, measured, parent["measurements"], initial["measurements"], - target=target, target_failure=target_failure, + settings, measured, parent["measurements"] if parent is not None else None, + initial["measurements"], target=target, target_failure=target_failure, ) - if parent is not None + if parent is not None or target is not None else {"passed": True, "metrics": {}} ) decision = evaluator.service_measurement_decision( diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 6ac157285..799e2c8c3 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -454,11 +454,29 @@ def test_stagnation_is_advisory_and_recover_does_not_retrigger(campaign): assert improved["stagnation"]["consecutive"] == 0 -def test_baseline_selected_final_has_no_self_gain_requirement(campaign): - begin(campaign) +@pytest.mark.parametrize(("target_kind", "target_value", "verdict"), [ + ("absolute", 110, "PASS"), + ("absolute", 95, "FAIL"), + ("relative_improvement_pct", 1, "FAIL"), +]) +def test_baseline_selected_final_checks_target_without_self_gain( + campaign, target_kind, target_value, verdict, +): + from tests.fixtures.campaign_intake import approved_start + + args = approved_start(campaign["start"], overrides={ + "protocol.target_kind": target_kind, "protocol.target_value": target_value, + }) + assert main(args) == 0 + campaign["capsys"].readouterr() + call(campaign, "baseline") + diagnose(campaign) submit(campaign, version="no-improvement", a=100) final = call(campaign, "final", "--reason", "No candidate selected") - assert final["final"]["assessment"]["verdict"] == "PASS" + assessment = final["final"]["assessment"] + assert assessment["verdict"] == verdict + if verdict == "FAIL": + assert assessment["reason"] == "final_performance_target_not_met" assert final["best"]["kind"] == "baseline" diff --git a/tests/harness/test_project_objectives.py b/tests/harness/test_project_objectives.py index 0a0dccdf7..75891f35a 100644 --- a/tests/harness/test_project_objectives.py +++ b/tests/harness/test_project_objectives.py @@ -80,6 +80,26 @@ def test_combined_gain_and_dual_limits_include_exact_boundary(): assert not evaluator.prefer_service_measurements(config, {"a": 101, "b": 10}, base["values"]) +@pytest.mark.parametrize(("kind", "limit", "passed"), [ + ("absolute", 110, True), + ("absolute", 95, False), + ("relative_improvement_pct", 1, False), +]) +def test_service_final_target_applies_without_a_comparison_parent(kind, limit, passed): + config = {"objectives": [objective()], "ranking": ["a"]} + baseline = {"values": {"a": 100}} + gate = evaluator.assess_service_performance( + config, baseline, None, baseline, target={"target_kind": kind, "target_value": limit}, + target_failure="final_performance_target_not_met", + ) + assert gate["passed"] is passed + decision = evaluator.service_measurement_decision("final", None, gate, {}) + if passed: + assert decision.assessment is None # Continue to the independent quality check. + else: + assert decision.assessment["reason"] == "final_performance_target_not_met" + + def test_screening_actual_gain_is_not_an_estimated_or_formal_threshold(): obj = objective() config = {"objectives": [obj]} From 944e6cb90a2411ed17692c3893ebec4743481e51 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Fri, 27 Nov 2026 11:01:40 +0800 Subject: [PATCH 25/26] Keep quality conversion within the existing evaluator import boundary Reuse the project evaluator module for the unit helpers shared by ordinary and service quality scoring. The Harness API retains its existing dependency graph. Agent-assisted-by: Codex (author) Signed-off-by: jiangkuaixue123 --- src/inferrsi/harness/evaluator/__init__.py | 3 +-- src/inferrsi/harness/evaluator/_project.py | 24 ++++++++++++++++++++- src/inferrsi/harness/evaluator/_quality.py | 25 ---------------------- src/inferrsi/harness/evaluator/_service.py | 3 +-- 4 files changed, 25 insertions(+), 30 deletions(-) delete mode 100644 src/inferrsi/harness/evaluator/_quality.py diff --git a/src/inferrsi/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py index 76df22621..09fa0e0a1 100644 --- a/src/inferrsi/harness/evaluator/__init__.py +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -16,8 +16,7 @@ relative_mad, validate_mechanism, ) -from ._project import assess_project, inspect_project_step, project_steps -from ._quality import quality_unit_declared +from ._project import assess_project, inspect_project_step, project_steps, quality_unit_declared from ._service import ( ServiceStageDecision, aggregate_service_measurements, diff --git a/src/inferrsi/harness/evaluator/_project.py b/src/inferrsi/harness/evaluator/_project.py index 2510c5e9a..c4a25920f 100644 --- a/src/inferrsi/harness/evaluator/_project.py +++ b/src/inferrsi/harness/evaluator/_project.py @@ -2,13 +2,13 @@ import json import math +from decimal import Decimal from pathlib import Path from statistics import median from inferrsi.harness.records.artifact_primitives import sha256 from ._measurement import explain, paired_statistics, profile_evidence, validate_mechanism -from ._quality import quality_score_in_unit def project_steps(settings: dict) -> list[dict]: @@ -48,6 +48,28 @@ def meets_target(target, *, baseline, candidate, direction): return (change if direction == "maximize" else -change) >= target["target_value"] +UNSPECIFIED_QUALITY_UNITS = ("", "unknown", "unspecified", "n/a") + + +def quality_unit_declared(unit) -> bool: + return isinstance(unit, str) and unit.strip().lower() not in UNSPECIFIED_QUALITY_UNITS + + +def quality_score_in_unit(score, reported_unit, approved_unit): + """Return the score in the frozen unit; only proportional scales can cross units.""" + if not (quality_unit_declared(reported_unit) and quality_unit_declared(approved_unit)): + raise ValueError("quality_unit_mismatch") + if reported_unit == approved_unit: + return score + scales = {"%": 2, "percent": 2, "fraction": 0, "ratio": 0} + if reported_unit not in scales or approved_unit not in scales: + raise ValueError("quality_unit_mismatch") + converted = float(Decimal(str(score)).scaleb(scales[approved_unit] - scales[reported_unit])) + if not math.isfinite(converted): + raise ValueError("quality_unit_mismatch") + return converted + + def inspect_project_step( directory: Path, settings: dict, definition: dict, execution: dict, ) -> dict: diff --git a/src/inferrsi/harness/evaluator/_quality.py b/src/inferrsi/harness/evaluator/_quality.py deleted file mode 100644 index 4c4d0a543..000000000 --- a/src/inferrsi/harness/evaluator/_quality.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Interpret scorer output in the unit declared by the frozen quality gate.""" - -import math -from decimal import Decimal - -UNSPECIFIED_QUALITY_UNITS = ("", "unknown", "unspecified", "n/a") - - -def quality_unit_declared(unit) -> bool: - return isinstance(unit, str) and unit.strip().lower() not in UNSPECIFIED_QUALITY_UNITS - - -def quality_score_in_unit(score, reported_unit, approved_unit): - """Return the score in the frozen unit; only proportional scales can cross units.""" - if not (quality_unit_declared(reported_unit) and quality_unit_declared(approved_unit)): - raise ValueError("quality_unit_mismatch") - if reported_unit == approved_unit: - return score - scales = {"%": 2, "percent": 2, "fraction": 0, "ratio": 0} - if reported_unit not in scales or approved_unit not in scales: - raise ValueError("quality_unit_mismatch") - converted = float(Decimal(str(score)).scaleb(scales[approved_unit] - scales[reported_unit])) - if not math.isfinite(converted): - raise ValueError("quality_unit_mismatch") - return converted diff --git a/src/inferrsi/harness/evaluator/_service.py b/src/inferrsi/harness/evaluator/_service.py index b950eb4b7..a6fcd1996 100644 --- a/src/inferrsi/harness/evaluator/_service.py +++ b/src/inferrsi/harness/evaluator/_service.py @@ -5,8 +5,7 @@ from statistics import mean, median from ..records import service_io -from ._project import meets_target -from ._quality import quality_score_in_unit +from ._project import meets_target, quality_score_in_unit def _metric_value(document, key): From e3438caa9e2414b39a7526a9de59efa50e5a9459 Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Fri, 27 Nov 2026 11:33:10 +0800 Subject: [PATCH 26/26] Replay the approved service performance gate during settlement Derive the attempt gate from the frozen plan and reference snapshots in one evaluator function. Both the executing attempt and the retained receipt validator use it, including final attempts that retain the baseline. Agent-assisted-by: Codex (author) Signed-off-by: jiangkuaixue123 --- src/inferrsi/harness/evaluator/__init__.py | 2 + src/inferrsi/harness/evaluator/_service.py | 20 ++++++ .../harness/evaluator/_service_evidence.py | 11 +--- .../harness/executor/serving/_attempt.py | 17 +---- tests/harness/test_project_objectives.py | 66 ++++++++++++++++--- 5 files changed, 81 insertions(+), 35 deletions(-) diff --git a/src/inferrsi/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py index 09fa0e0a1..a1bfba2ff 100644 --- a/src/inferrsi/harness/evaluator/__init__.py +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -20,6 +20,7 @@ from ._service import ( ServiceStageDecision, aggregate_service_measurements, + assess_service_attempt_performance, assess_service_performance, check_service_quality_reference, prefer_service_measurements, @@ -49,6 +50,7 @@ "aggregate_service_measurements", "assess_ordinary", "assess_project", + "assess_service_attempt_performance", "assess_service_performance", "check_service_quality_reference", "explain", diff --git a/src/inferrsi/harness/evaluator/_service.py b/src/inferrsi/harness/evaluator/_service.py index a6fcd1996..9e74f6e70 100644 --- a/src/inferrsi/harness/evaluator/_service.py +++ b/src/inferrsi/harness/evaluator/_service.py @@ -108,6 +108,26 @@ def assess_service_performance(settings, measured, parent, initial, *, screening return {"passed": passed, "metrics": metrics, "reason": reason} +def assess_service_attempt_performance(plan, attempt, measured): + """Apply the frozen gates identically during execution and evidence replay.""" + role = attempt["role"] + target = None + failure = "performance_gate_not_met" + if role == "candidate" and "candidate_min_improvement_pct" in plan: + target = {"target_kind": "relative_improvement_pct", + "target_value": plan["candidate_min_improvement_pct"]} + elif role == "final": + target = plan.get("performance_target") + failure = "final_performance_target_not_met" + parent = attempt["parent"] + if parent is None and target is None: + return {"passed": True, "metrics": {}} + return assess_service_performance( + plan["evaluation_settings"], measured, None if parent is None else parent["measurements"], + attempt["initial"]["measurements"], target=target, target_failure=failure, + ) + + def prefer_service_measurements(settings, left, right): by_id = {obj["id"]: obj for obj in settings["objectives"]} for name in settings["ranking"]: diff --git a/src/inferrsi/harness/evaluator/_service_evidence.py b/src/inferrsi/harness/evaluator/_service_evidence.py index 830c6320f..fb80dd4a1 100644 --- a/src/inferrsi/harness/evaluator/_service_evidence.py +++ b/src/inferrsi/harness/evaluator/_service_evidence.py @@ -111,16 +111,7 @@ def receipt(stage): measured = _service.aggregate_service_measurements(settings, docs, role) if measured != execution["measurements"]: return "unverifiable_evaluation_evidence" - gate = ( - _service.assess_service_performance( - settings, - measured, - record["parent"]["measurements"], - record["initial"]["measurements"], - ) - if record["parent"] - else {"passed": True, "metrics": {}} - ) + gate = _service.assess_service_attempt_performance(plan, record, measured) if gate != assessed["performance"]: return "unverifiable_evaluation_evidence" # Refreshed comparison parents supply performance only; the initial run owns quality. diff --git a/src/inferrsi/harness/executor/serving/_attempt.py b/src/inferrsi/harness/executor/serving/_attempt.py index 6014c5722..74e52ad4d 100644 --- a/src/inferrsi/harness/executor/serving/_attempt.py +++ b/src/inferrsi/harness/executor/serving/_attempt.py @@ -206,22 +206,7 @@ def evaluate(role): record["failed_stage"], error = first_failure raise error measured = evaluator.aggregate_service_measurements(settings, docs, role) - target = None - target_failure = "performance_gate_not_met" - if role == "candidate" and "candidate_min_improvement_pct" in plan: - target = {"target_kind": "relative_improvement_pct", - "target_value": plan["candidate_min_improvement_pct"]} - elif role == "final": - target = plan.get("performance_target") - target_failure = "final_performance_target_not_met" - gate = ( - evaluator.assess_service_performance( - settings, measured, parent["measurements"] if parent is not None else None, - initial["measurements"], target=target, target_failure=target_failure, - ) - if parent is not None or target is not None - else {"passed": True, "metrics": {}} - ) + gate = evaluator.assess_service_attempt_performance(plan, pending, measured) decision = evaluator.service_measurement_decision( role, pending.get("reference_kind"), gate, settings["quality"], ) diff --git a/tests/harness/test_project_objectives.py b/tests/harness/test_project_objectives.py index 75891f35a..d1da036f5 100644 --- a/tests/harness/test_project_objectives.py +++ b/tests/harness/test_project_objectives.py @@ -1,10 +1,12 @@ """Pure objective boundaries; these numbers are test controls, never campaign defaults.""" import copy +import json import pytest from inferrsi.harness import evaluator +from inferrsi.harness.evaluator import _service_evidence def test_service_decisions_use_the_recorded_role_and_performance_gate(): @@ -85,19 +87,65 @@ def test_combined_gain_and_dual_limits_include_exact_boundary(): ("absolute", 95, False), ("relative_improvement_pct", 1, False), ]) -def test_service_final_target_applies_without_a_comparison_parent(kind, limit, passed): - config = {"objectives": [objective()], "ranking": ["a"]} - baseline = {"values": {"a": 100}} - gate = evaluator.assess_service_performance( - config, baseline, None, baseline, target={"target_kind": kind, "target_value": limit}, - target_failure="final_performance_target_not_met", - ) +def test_service_final_target_replays_without_a_comparison_parent(tmp_path, kind, limit, passed): + obj = dict(objective(), scenario="workload", key="metric", aggregate="median", + domain={"min": 0, "max": 1000}) + config = { + "objectives": [obj], "ranking": ["a"], + "sampling": {"final": {"warmups": 0, "repetitions": 1}}, + "scenarios": [ + {"id": "workload", "workload": "fixture", "requests": 1, "required_successes": 1}, + ], + "quality": {"mode": "absolute", "direction": "minimize", "threshold": 1, + "key": "score", "dataset": "fixture", "scorer": "exact", "samples": 1, + "unit": "%"}, + } + plan = {"evaluation_settings": config, + "performance_target": {"target_kind": kind, "target_value": limit}} + measured = {"values": {"a": 100}, "samples": {"a": [100]}} + binding = {"attempt_id": "attempt", "revision": "revision", "service_id": "service", + "run_id": "run", "conditions": {"effective_config": {}}, "effective_config": {}} + final = {**binding, "role": "final", "parent": None, "path": "final/attempt", + "initial": {"measurements": measured, "quality_score": 0.5}} + gate = evaluator.assess_service_attempt_performance(plan, final, measured) assert gate["passed"] is passed - decision = evaluator.service_measurement_decision("final", None, gate, {}) + decision = evaluator.service_measurement_decision("final", None, gate, config["quality"]) + + def retain(path, **data): + target = tmp_path / final["path"] / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(data), encoding="utf-8") + + retain("request.json", **binding) + retain("effective-config.json") + retain("service/owner.json", **binding, pid=123, cwd="fixture") + retain("execution/precheck/result.json", status="completed", passed=True) + retain("execution/ready/result.json", binding=binding, status="completed", ready=True, + ownership="local_process_domain", owner_pid=123, loaded_root="fixture", + loaded_revision=binding["revision"]) + retain("execution/measure-001/result.json", binding=binding, status="completed", + scenarios={ + "workload": {"workload": "fixture", "requests": 1, "successes": 1, + "metric": 100, "units": {"a": "ms"}}, + }) + + quality_score = None if passed: - assert decision.assessment is None # Continue to the independent quality check. + assert decision.assessment is None + retain("execution/quality/result.json", binding=binding, status="completed", + dataset="fixture", scorer="exact", samples=1, unit="fraction", score=0.005) + quality_score = 0.5 + decision = evaluator.service_quality_decision("final", gate, True) + assert decision.assessment["verdict"] == "PASS" else: assert decision.assessment["reason"] == "final_performance_target_not_met" + final.update(execution={"binding": binding, "measurements": measured, + "quality_score": quality_score}, assessment=decision.assessment) + assert _service_evidence.evaluation_reason(tmp_path, plan, final) is None + final["assessment"]["performance"]["passed"] = not passed + assert _service_evidence.evaluation_reason( + tmp_path, plan, final + ) == "unverifiable_evaluation_evidence" def test_screening_actual_gain_is_not_an_estimated_or_formal_threshold():