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/apps-module-migrations.json b/docs/apps-module-migrations.json index f195dc525..e0d4bfbb3 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -584,6 +584,8 @@ "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", "src/inferrsi/apps/delivery/snapshot.py", diff --git a/docs/guides/operations.md b/docs/guides/operations.md index babb4499c..d01cde876 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` 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) | @@ -530,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/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 850341470..dea7d37e0 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -170,14 +170,17 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 下面是命令结构;尖括号是需要落实的项目条件,不是可直接执行的默认值。命令以 argv 执行,不经 shell;Windows 命令参数中的路径建议用正斜杠。 +启动前,按[任务确认流程](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}"' \ --quality-command '"{python}" "{protocol}/quality.py" --project "{candidate}" --reference "{baseline}" --result "{result}"' \ --metric-key --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 @@ -194,6 +197,7 @@ assessment 另附 `paired_statistics`:同一次重复内的第 k 个基线与 结果协议: - 测量脚本正常结束并写 JSON,提供指定字段的有限正数。 +- 对于有评分的结果,质量脚本在顶层 `dataset` 字段自行报告数据集、版本和切分标识。Harness 将它与已批准的 `--quality-benchmark` 核对;缺少标识或标识不一致时,该评分结果为 `INCONCLUSIVE`。 - 质量脚本正常结束并写 JSON,提供指定字段的严格布尔值。`false` 拒绝候选;基线拒绝说明协议/基线前提不成立。 - 脚本可捕获已知候选错误,正常结束并写 `{"status":"candidate_failure","reason":"..."}`。候选失败保留为 FAIL 并消耗一轮,后续可修改。不要把设备故障捕获成候选错误。 - 非零退出、超时、缺少或无法解析的输出不猜测为正确性失败,而是 INCONCLUSIVE,阻止继续把缺失证据当成有效比较。 diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 2ef4e82d6..514178648 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. @@ -116,8 +122,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 @@ -300,6 +308,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-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..780c49aaf --- /dev/null +++ b/docs/guides/task-intake.md @@ -0,0 +1,242 @@ +# 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` update the named record under a sibling `.lock` file. +If an update is in progress, retry after it finishes. + +## 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.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} + }, + "open_questions": [], + "blockers": [], + "conflicts": [], + "allowed_next": ["read_only_preparation"], + "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 | +| `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. + +## 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. 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. 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 + every stage named in `required_before`. +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. + +## Acceptance boundary + +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 \ + --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 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 +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. If the +user selects a different acceptance reference after returning the brief, pass +that correction to `evaluate --set acceptance.reference=...` with the new +`--frozen` file when applicable. Intake discards values bound to the former +authority. +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 + +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 +``` + +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. +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 +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. 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 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. +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 + +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/docs/searchspace-index.json b/docs/searchspace-index.json index d5eefeacc..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": "f4399276c8389f33ad81a2a25ccd0ff4392a37635ae9c53943ece4995c84d246" + "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 4d92f1500..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:b1f3b477729a45ae923a5365d905c2715c5aac9d08a09d2dde92017c7aea2a09` +- Input digest: `sha256:f3e30fec6b9e63c740c60eafe545c7032654e844c9d4a021715f55e028bceb75` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index d039ebeff..5706acc5d 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -70,6 +70,60 @@ 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 + +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 --json +``` + +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. +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. + +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 +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 Default to the current Agent conversation. Read `campaign start --help` through @@ -87,6 +141,12 @@ 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`. +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. 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/__init__.py b/src/inferrsi/apps/cli/__init__.py index f5b12cdf7..be3fcf7c0 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -51,7 +51,8 @@ def _session_request(args): if field.name in values}) -def _optimization_session(args, *, task_source=None, report_metadata=None): +def _optimization_session(args, *, task_source=None, report_metadata=None, + prepare_project_only=False): from ...harness.executor import assess_packaged_task from ...harness.manager import run_session from ...knowledge.ranking_policy import managed_ranking_policy @@ -72,7 +73,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, prepare_project_only=prepare_project_only, ) @@ -366,9 +367,15 @@ 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 or probe. Only + ``task intake`` writes, and only its ``--record`` file. + """ 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()) @@ -885,7 +892,15 @@ def main(argv: list[str] | None = None) -> int: if getattr(args, "session_action", None) is not None: from ..delivery import after_final - result = _optimization_session(args) + if args.session_action == "start" and getattr(args, "project_task", False): + from .campaign_intake import start + + 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 ec88af237..5f43fa7de 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -183,6 +183,11 @@ 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("--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") @@ -191,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) @@ -543,7 +551,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 ( @@ -557,6 +565,38 @@ 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="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") + 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/campaign_intake.py b/src/inferrsi/apps/cli/campaign_intake.py new file mode 100644 index 000000000..06485db9e --- /dev/null +++ b/src/inferrsi/apps/cli/campaign_intake.py @@ -0,0 +1,182 @@ +"""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.executor import service_revision +from ...harness.executor.candidates import identity +from ...harness.manager import initialize_session +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): + 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_unit": quality["unit"], + "protocol.quality_benchmark": quality["dataset"], + "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"], + "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 = 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.quality_benchmark": settings["quality_benchmark"], + "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(): + 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"): + approved = shlex.split(approved) + elif ( + key == "acceptance.baseline_revision" + and args.evaluation_mode == "abba" + and approved != actual + and (args.repo / ".git").exists() + ): + if actual == identity(args.repo, args.include): + actual = 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, prepare_project_only=True) + plan = frozen["plan"] + 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) + 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": + plan["candidate_min_improvement_pct"] = conditions["acceptance.min_improvement_pct"] + 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 = initialize_session(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 new file mode 100644 index 000000000..b6536d2c4 --- /dev/null +++ b/src/inferrsi/apps/cli/intake_contract.py @@ -0,0 +1,793 @@ +"""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 + +import copy +import hashlib +import json +import math + +from ...harness.evaluator import quality_unit_declared +from . import task_input + +SCHEMA_VERSION = 1 + +STAGES = ( + "read_only_preparation", + "baseline_measurement", + "candidate_search", + "service_execution", + "device_execution", +) +BLOCKING_STAGES = STAGES[1:] + +MAP_TARGETS = ("task-input/v1", "campaign-protocol", "session-protocol", + "summary-only", "day0-spec") + +STATUSES = ("confirmed", "proposed", "assumed", "unknown", "conflicting", + "stale", "superseded") +SETTLED = ("confirmed", "proposed") +BLOCKING = ("unknown", "assumed", "conflicting", "stale", "superseded") + +ACCEPTANCE = "acceptance." +AUTHORITATIVE = ("issue", "frozen_gate") +REFERENCE = "acceptance.reference" + +_QUESTION = "q:" +_BRIEF_QUESTION = "q:task_brief:" + + +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 (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) + 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") + 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) + 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: + 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]: + 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") + 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") + 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 + 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: + 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"), str): + bad(path, "source must be a string") + if entry.get("status") in SETTLED: + try: + _typed_value(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 + + +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 _typed_value(field: dict, value: object) -> object: + kind = field.get("type", "text") + if kind == "number": + if isinstance(value, bool) or not isinstance(value, (str, int, float)): + raise IntakeError("invalid_value", f"{field['path']} must be a finite 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 + 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 _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}") + 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 + + +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 _card_source(path, source) + + +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 _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) + 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") or path == "protocol.quality_unit": + try: + _coerce(field, entry.get("value")) + except IntakeError: + 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(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: + 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 + + +def _bump(record: dict, next_revision: int) -> None: + record.pop("brief_decision", None) + record.pop("campaign_launch", 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: + 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 = 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) + 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 + updated["fields"][path] = entry + changed = True + continue + if (current is not None and current.get("status") == "conflicting" + and isinstance(current.get("candidates"), list)): + 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): + 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 + elif _rank(status) < _rank(current["status"]): + continue + 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 + if current is not None and current.get("asked") and status != "assumed": + entry["asked"] = True + updated["fields"][path] = entry + changed = True + if changed: + _bump(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, 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["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"]] + card = { + "field": field["path"], + "batch": field.get("batch", 1), + "question": field["question"], + "options": options, + "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]: + 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 _service_quality_line(quality: dict, unit: str) -> str: + 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 "+" + 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)") + + +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 = str(values["protocol.target_value"]).removesuffix(".0") + if values["protocol.target_kind"] == "relative_improvement_pct": + 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} {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"{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} + if "campaign_launch" in record: + 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") + 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 + + +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: + """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) + 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["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) + question_fields = [field for field in missing if field.get("batch", 1) == lowest] + questions = [_question(record, 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 ( + stage == "candidate_search" and 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: + 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) + 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} + 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, + "needs_user_input": bool(questions) or review == "changes_requested", + "brief_review": review, + "task_brief": brief, + "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: + """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") + 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") + 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", + 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: + raise IntakeError("unknown_question", + f"{question_id} names a field outside {spec['task']}; re-evaluate") + if _question(record, field)["id"] != question_id: + 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", "assumed", + ): + 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: + 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 + + +def summary(record: dict, spec: dict, *, frozen: dict | None = None) -> dict: + view = evaluate(record, spec, frozen=frozen) + confirmed, proposed, unknown = {}, {}, [] + for field in spec["fields"]: + path = field["path"] + entry = view["fields"].get(path, {}) + status = entry.get("status", "unknown") + if status == "confirmed": + confirmed[path] = entry.get("value") + elif status in ("proposed", "assumed"): + 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"], + "record_id": record["record_id"], + "revision": view["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, + "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_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 new file mode 100644 index 000000000..4d9c565b9 --- /dev/null +++ b/src/inferrsi/apps/cli/task_intake.py @@ -0,0 +1,353 @@ +"""intake/v1 CLI: load spec and record, apply ``intake_contract``, write the record back.""" + +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +import uuid +from importlib.resources import files +from pathlib import Path + +from ..storage.artifacts import file_lock +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"] + return {f"acceptance.{name}": value for name, value in acceptance.items() + if name != "reference" and preview["sources"][f"acceptance.{name}"] == "yaml"} + + +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: + 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"] + record["allowed_next"] = view["allowed_next"] + record["complete"] = view["complete"] + write_record(path, record) + + +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) + 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: + 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: + 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", + } + 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 + + +def evaluate_command(args) -> dict: + record_path = Path(args.record) + existing = record_path.is_file() + if existing: + 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"]) + 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]: + 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") + 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=bind_file) + + +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)) + 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: + record = read_record(Path(args.record)) + spec = load_spec(record["task"]) + record, frozen = _evaluate_gate(record, spec, args.frozen, selecting_reference=False) + return intake.summary(record, spec, frozen=frozen) + + +def campaign_gate(path: Path, *, expected_task: str = "task-performance", + frozen: dict | None = None) -> tuple[dict, dict]: + """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: + 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 { + "status": "ready" if view["complete"] else "blocked", + "task": expected_task, + "record": str(path), + "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"], + "execution": "not started", + }, 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) + return {"intake": { + "record": "intake.json", + "task": record["task"], + "revision": record["revision"], + "sha256": digest, + "brief_id": gate["task_brief"]["id"], + "gate": gate["status"], + }} + + +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()), + *([json.dumps(brief["campaign_launch"], ensure_ascii=False, indent=2)] + if "campaign_launch" in brief else [])] + + +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']}") + 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_brief(view)) + 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'}"] + lines.extend(_render_brief(view)) + 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 == "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)) + 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/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py index 2eee432cf..a1bfba2ff 100644 --- a/src/inferrsi/harness/evaluator/__init__.py +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -16,10 +16,11 @@ relative_mad, validate_mechanism, ) -from ._project import assess_project, inspect_project_step, project_steps +from ._project import assess_project, inspect_project_step, project_steps, quality_unit_declared 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", @@ -62,6 +64,7 @@ "prefer_service_measurements", "profile_evidence", "project_steps", + "quality_unit_declared", "relative_mad", "service_assessment", "service_choice", @@ -83,7 +86,9 @@ def assess_ordinary(root, directory, plan, execution, mechanism=None, *, assess_packaged): """Read project evidence or delegate to the packaged task's supplied assessor.""" if plan["task_source"] == "project": + target = plan.get("performance_target") if directory.parent == root / "final" else None return assess_project( - directory, plan["evaluation_settings"], execution, mechanism=mechanism, + directory, plan["evaluation_settings"], execution, + mechanism=mechanism, final_target=target, ) return assess_packaged(root, directory, plan, execution) diff --git a/src/inferrsi/harness/evaluator/_project.py b/src/inferrsi/harness/evaluator/_project.py index ca0c2630a..c4a25920f 100644 --- a/src/inferrsi/harness/evaluator/_project.py +++ b/src/inferrsi/harness/evaluator/_project.py @@ -2,6 +2,7 @@ import json import math +from decimal import Decimal from pathlib import Path from statistics import median @@ -33,6 +34,42 @@ 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"] + + +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: @@ -52,7 +89,29 @@ def inspect_project_step( 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: + score = _value(document, bound["metric"]) + 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"]] if rejected or (definition["phase"] == "quality" and quality is False): return {"status": ("candidate_failure" if definition["side"] == "candidate" else "infrastructure_failure"), @@ -73,7 +132,7 @@ def inspect_project_step( def assess_project(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 = {} @@ -165,6 +224,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" @@ -195,6 +261,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/evaluator/_service.py b/src/inferrsi/harness/evaluator/_service.py index 040fab1d9..9e74f6e70 100644 --- a/src/inferrsi/harness/evaluator/_service.py +++ b/src/inferrsi/harness/evaluator/_service.py @@ -1,9 +1,11 @@ """Decide service stages from frozen rules and already collected receipts.""" from dataclasses import dataclass +from decimal import Decimal from statistics import mean, median from ..records import service_io +from ._project import meets_target, quality_score_in_unit def _metric_value(document, key): @@ -62,9 +64,11 @@ def service_metric_change(obj, candidate, reference): return delta -def assess_service_performance(settings, measured, parent, initial, *, screening=False): +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]) @@ -90,12 +94,38 @@ 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) - return { - "passed": passed, - "metrics": metrics, - "reason": "performance_gate_satisfied" if passed else "performance_gate_not_met", - } + 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] + objective = next(obj for obj in settings["objectives"] if obj["id"] == name) + passed = meets_target(target, baseline=initial["values"][name], + candidate=measured["values"][name], direction=objective["direction"]) + if passed is None: + raise ValueError("Undefined relative performance target against the baseline") + if not passed: + reason = target_failure + 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): @@ -121,7 +151,10 @@ def service_quality_score(settings, document): or document["samples"] != config["samples"] ): raise ValueError("Missing numerical quality evidence") - return score + # Retained pre-intake plans used scores in the scorer's native scale. + if "unit" not in config: + return score + return quality_score_in_unit(score, document.get("unit"), config["unit"]) def service_quality_passed(settings, score, reference=None): @@ -131,7 +164,10 @@ def service_quality_passed(settings, score, reference=None): return sign * (score - config["threshold"]) >= 0 if reference is None or not service_io.finite_number(reference): raise ValueError("Missing compatible baseline quality reference") - return sign * (score - reference) >= -config["tolerance"] + if "unit" not in config: + return sign * (score - reference) >= -config["tolerance"] + delta = Decimal(str(score)) - Decimal(str(reference)) + return sign * delta >= -Decimal(str(config["tolerance"])) def service_assessment(verdict, reason, **fields): @@ -175,8 +211,9 @@ def service_measurement_decision(role, reference_kind, gate, quality): skipped = ((("quality",), "performance_gate_not_met"),) if role != "candidate": skipped += ((("profile",), "not_required"),) + reason = gate.get("reason", "performance_gate_not_met") return ServiceStageDecision( - service_assessment("FAIL", "performance_gate_not_met", performance=gate), + service_assessment("FAIL", reason, performance=gate), skipped, ) if reference_kind == "parent": 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/_project.py b/src/inferrsi/harness/executor/_project.py index b15f773bc..0d8672de4 100644 --- a/src/inferrsi/harness/executor/_project.py +++ b/src/inferrsi/harness/executor/_project.py @@ -22,6 +22,10 @@ def validate_project(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: diff --git a/src/inferrsi/harness/executor/serving/_attempt.py b/src/inferrsi/harness/executor/serving/_attempt.py index c404a21dc..74e52ad4d 100644 --- a/src/inferrsi/harness/executor/serving/_attempt.py +++ b/src/inferrsi/harness/executor/serving/_attempt.py @@ -206,13 +206,7 @@ def evaluate(role): record["failed_stage"], error = first_failure raise error measured = evaluator.aggregate_service_measurements(settings, docs, role) - gate = ( - evaluator.assess_service_performance( - settings, measured, parent["measurements"], initial["measurements"] - ) - if parent 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/src/inferrsi/harness/executor/serving/_plan.py b/src/inferrsi/harness/executor/serving/_plan.py index d7c979f11..97ba0b886 100644 --- a/src/inferrsi/harness/executor/serving/_plan.py +++ b/src/inferrsi/harness/executor/serving/_plan.py @@ -6,6 +6,7 @@ import time from pathlib import Path +from ...evaluator import quality_unit_declared from ...records import service_io from ...records.atomic_json import atomic_write_json from ..candidates import members, retain @@ -24,7 +25,7 @@ def validate_service_conditions(conditions): service_io.no_fingerprints(conditions) -def validate_service_settings(settings): +def validate_service_settings(settings, *, require_quality_unit=False): service_io.no_fingerprints(settings) for name in ("conditions", "commands", "sampling", "quality", "stagnation"): if not isinstance(settings.get(name), dict): @@ -139,6 +140,10 @@ def validate_service_settings(settings): ) ): raise ValueError("Declare quality mode, direction, dataset, scorer and key") + if (require_quality_unit or "unit" in quality) and not quality_unit_declared( + quality.get("unit") + ): + raise ValueError("Declare an explicit quality unit") 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") @@ -232,7 +237,7 @@ def prepare_service(root, args): from inferrsi import __version__ settings = service_io.read(args.evaluation_config) - validate_service_settings(settings) + validate_service_settings(settings, require_quality_unit=True) source, protocol = args.repo.resolve(), args.protocol.resolve() if args.repo.is_symlink() or args.protocol.is_symlink(): raise ValueError("Project and protocol roots cannot be symbolic") diff --git a/src/inferrsi/harness/manager/__init__.py b/src/inferrsi/harness/manager/__init__.py index 44e783b3e..e277e3c73 100644 --- a/src/inferrsi/harness/manager/__init__.py +++ b/src/inferrsi/harness/manager/__init__.py @@ -34,6 +34,7 @@ from ._runner import run_experiment from ._runtime import session_runtime_identity from ._session import run_session +from ._state import initialize as initialize_session from ._state import read_session_records from .search._engine import EngineSearchPlan, read_engine_search, run_engine_search @@ -43,7 +44,7 @@ "ReadSessionKnowledge", "RecoverSession", "RefreshSessionReferences", "ResumeSession", "SessionRequest", "SessionStatus", "StartBenchmarkSession", "StartProjectSession", - "read_session_records", "run_session", + "initialize_session", "read_session_records", "run_session", "AGENT_TERMINAL_STATES", "agent_session_status", "bind_agent_session", "dispatch_agent_session", "prepare_agent_session", "record_agent_session", "EngineSearchPlan", "read_engine_search", "run_engine_search", "run_experiment", diff --git a/src/inferrsi/harness/manager/_requests.py b/src/inferrsi/harness/manager/_requests.py index c0a5b2002..7ebd2a31a 100644 --- a/src/inferrsi/harness/manager/_requests.py +++ b/src/inferrsi/harness/manager/_requests.py @@ -47,6 +47,7 @@ class StartProjectSession(_StartSession): metric_key: str | None = None metric_unit: str | None = None quality_key: str | None = None + quality_benchmark: str | None = None scope: str | None = None direction: Literal["minimize", "maximize"] | None = None min_improvement_pct: float | None = None diff --git a/src/inferrsi/harness/manager/_session.py b/src/inferrsi/harness/manager/_session.py index 88cf6326f..ef7941675 100644 --- a/src/inferrsi/harness/manager/_session.py +++ b/src/inferrsi/harness/manager/_session.py @@ -18,6 +18,7 @@ def run_session( task_source: Path | None = None, knowledge_reader=None, prepare_context=None, external_knowledge=None, external_provider=None, external_project=None, external_provider_for=None, report_metadata=None, + prepare_project_only=False, ) -> dict: """Run one typed session operation with dependencies supplied by the host.""" from .. import evaluator, executor, indexer @@ -26,6 +27,8 @@ def run_session( if not isinstance(request, SessionRequest): raise TypeError("run_session requires a managed session request") + if prepare_project_only and not isinstance(request, StartProjectSession): + raise ValueError("Only project starts can prepare without initializing a session") root = request.session.resolve() if isinstance(request, (StartProjectSession, StartBenchmarkSession)): project = isinstance(request, StartProjectSession) @@ -72,6 +75,7 @@ def run_session( "metric_key", "metric_unit", "quality_key", + "quality_benchmark", "scope", "direction", "min_improvement_pct", @@ -111,7 +115,7 @@ def run_session( **({"allow_final_continuation": True} if allow_continuation else {}), **settings, } - result = state.initialize(root, plan) + result = {"plan": plan} if prepare_project_only else state.initialize(root, plan) result["instructions"] = ( "Run campaign baseline before candidate search. Record the measured " "bottleneck with campaign diagnose before knowledge or rounds. " @@ -133,7 +137,8 @@ def run_session( raise ValueError("Campaign output must be outside the editable project") identity(repo, request.include) # Reject invalid inputs before preparation writes. specification = {key: getattr(request, 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(request.measure_command), @@ -180,7 +185,7 @@ def run_session( plan["external_knowledge_project"] = external_project if report_metadata is not None: plan["report_metadata"] = report_metadata - result = state.initialize(root, plan) + result = {"plan": plan} if prepare_project_only else state.initialize(root, plan) operation = "campaign" if project else "benchmarks session" result["instructions"] = ( f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 3abf1a04e..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": "bf14fec0bd909efcfeb2bc02d69fe227d0c51ce6", + "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 93037ddac..4fc6071a2 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": "46b44df9d2b6b91ae305df21536d9cf04903b3ea442b0413b3f2319452faafb9", + "intake.json": "13ecae20885d7ea07bbb00b84be3481f4a825590e2e4044abd6cdb2d6bcaf680" } }, "task-version-alignment": { 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..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 @@ -34,12 +34,52 @@ 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 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. + +## 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. + +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. +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 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..8a419ac33 --- /dev/null +++ b/src/inferrsi/knowledge/data/skill_library/tasks/task-performance/intake.json @@ -0,0 +1,309 @@ +{ + "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", + "user_choice": true, + "maps_to": "task-input/v1", + "batch": 1, + "type": "text", + "question": "Which outcome decides this round?", + "required_before": ["baseline_measurement", "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": ["baseline_measurement", "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": "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, + "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", + "user_choice": true, + "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", + "user_choice": true, + "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", + "user_choice": true, + "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", + "user_choice": true, + "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", + "user_choice": true, + "maps_to": "task-input/v1", + "batch": 2, + "type": "number", + "question": "What time budget bounds the whole round?", + "required_before": ["baseline_measurement"] + }, + { + "path": "protocol.comparison", + "user_choice": true, + "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", + "user_choice": true, + "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", + "user_choice": true, + "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", + "user_choice": true, + "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_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py index b1eadd835..c0c748fa5 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,15 +68,17 @@ 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}"', "--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"]), ) 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 dcb86c979..4adacc37d 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.manager import read_session_records from inferrsi.harness.records.artifact_primitives import digest +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 @@ -46,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" @@ -56,18 +58,19 @@ 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", '"{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, - ]) + ])) 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 a181c91dc..1b805687e 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -11,6 +11,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.harness.manager import read_session_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 @@ -32,7 +33,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" @@ -50,7 +52,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, @@ -58,7 +61,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" @@ -168,7 +172,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, ) @@ -271,7 +275,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) @@ -426,7 +431,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() @@ -524,7 +529,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") @@ -656,7 +661,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_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index c6bbff567..799e2c8c3 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -14,10 +14,11 @@ from inferrsi.apps.cli import main from inferrsi.apps.cli.arguments import parser from inferrsi.apps.delivery import project, read_bundle -from inferrsi.harness import executor, manager +from inferrsi.harness import evaluator, executor, manager from inferrsi.harness.executor.serving import _attempt from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records import service_io +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 @@ -95,8 +96,16 @@ def test_manager_baseline_and_cli_status_share_one_service_attempt(campaign, mon 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) @@ -445,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" @@ -604,17 +631,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): @@ -866,6 +898,18 @@ def test_invalid_protocol_containers_rejected_before_campaign_writes(campaign, b assert not campaign["root"].exists() +@pytest.mark.parametrize("unit", [None, "", "unknown", " N/A ", "unspecified"]) +def test_missing_or_placeholder_quality_unit_rejected_before_campaign_writes(campaign, unit): + config = settings() + if unit is None: + config["quality"].pop("unit") + else: + 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 @@ -906,6 +950,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, } @@ -934,7 +979,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)) @@ -1775,7 +1820,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() @@ -1793,3 +1838,211 @@ 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 = service_io.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 + 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 evaluator.service_quality_passed(config, good, reference=90) + assert not evaluator.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", 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]) + 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" + 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 + 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() + + +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() + + +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() + + +@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 = service_io.read(campaign["root"] / "plan.json")["evaluation_settings"] + receipt = {"dataset": "synthetic", "scorer": "exact-v1", "samples": 2, + "quality": baseline, "unit": "%"} + reference = evaluator.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"): + evaluator.service_quality_score(frozen, receipt) + else: + normalized = evaluator.service_quality_score(frozen, receipt) + passed = evaluator.service_quality_passed(frozen, normalized, reference) + assert passed is (verdict == "PASS") diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 1391378ee..4c39fa5b0 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -398,7 +398,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] diff --git a/tests/apps/test_task_intake.py b/tests/apps/test_task_intake.py new file mode 100644 index 000000000..06eb8fa46 --- /dev/null +++ b/tests/apps/test_task_intake.py @@ -0,0 +1,1028 @@ +"""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 +from tests.fixtures.campaign_intake import approved_start + +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 path in COMPLETE["fields"]["values"]} + accepted = {path: value for path, value in chosen.items() + 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 + + +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 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} + + +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 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() + 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(): + 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", 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", + 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) + 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, {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" + + +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"} + + +@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": "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}", + "--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=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) + 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"} + 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", "record.json.lock"} + + +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 + + +def test_matching_frozen_gate_keeps_a_complete_record_complete(): + frozen = task_intake.frozen_values(PERFORMANCE / "frozen-gate.yaml") + view = intake.evaluate(approved_record(), 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) + 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): + 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(approved_record()), encoding="utf-8") + gate, gated = task_intake.campaign_gate(complete) + assert gate["status"] == "ready" + assert gate["complete"] is True + assert gated == approved_record() + + +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 + 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_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"] + assert cli.main(["campaign", "status", "--directory", str(project[3])]) == 0 + + +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(): + 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" + + +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() + + 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() + reference_card = card_id(task_intake.read_record(record), intake.REFERENCE) + answer = ["task", "intake", "answer", "--record", str(record), "--question", + 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:" + 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"][ + "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_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)} + 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 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" + + +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=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=card_id(record, "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=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"] + 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=card_id(edited, "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" + + +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"] + +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), + ("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"): + token = card_id(task_intake.read_record(path), key) + assert cli.main(["task", "intake", "answer", "--record", str(path), "--json", + "--question", token, "--value", "1"]) == 0 + view = json.loads(capsys.readouterr().out) + assert view["brief_review"] == "awaiting_confirmation" + 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"), + ("--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 + 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" + "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, + "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 + + +@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,'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" + "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") + + +@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 == "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_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"] + 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" diff --git a/tests/fixtures/campaign_intake.py b/tests/fixtures/campaign_intake.py new file mode 100644 index 000000000..1f9da1bfa --- /dev/null +++ b/tests/fixtures/campaign_intake.py @@ -0,0 +1,130 @@ +"""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 executor +from inferrsi.harness.executor import candidates +from inferrsi.harness.records import service_io + + +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 = service_io.read(args.evaluation_config) + executor.validate_service_settings(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": executor.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_unit": q["unit"], + "protocol.quality_comparator": 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_benchmark": args.quality_benchmark, + "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/intake/performance/complete.json b/tests/fixtures/intake/performance/complete.json new file mode 100644 index 000000000..648c109dc --- /dev/null +++ b/tests/fixtures/intake/performance/complete.json @@ -0,0 +1,45 @@ +{ + "task": "task-performance", + "description": "All field decisions are supplied. A separate reply must approve the task brief.", + "fields": { + "source": "prompt", + "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", + "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", + "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": { + "source": "issue", + "values": { + "acceptance.metric_key": "p95_ttft", + "acceptance.metric_unit": "ms", + "acceptance.direction": "minimize", + "acceptance.min_improvement_pct": 10, + "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": {} + } +} diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index 4e53452f0..69147a29e 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -12,6 +12,7 @@ from inferrsi.apps.storage import artifacts from inferrsi.harness.records import artifact_primitives, 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 @@ -120,6 +121,7 @@ def settings(): "mode": "absolute", "dataset": "synthetic", "scorer": "exact-v1", + "unit": "points", "samples": 2, "key": "quality", "direction": "maximize", @@ -174,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)] ) @@ -207,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 diff --git a/tests/fixtures/service_reuse_protocol.py b/tests/fixtures/service_reuse_protocol.py index 4c3cf3ca0..cd1a3e1b1 100644 --- a/tests/fixtures/service_reuse_protocol.py +++ b/tests/fixtures/service_reuse_protocol.py @@ -70,6 +70,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_project_objectives.py b/tests/harness/test_project_objectives.py index 0a0dccdf7..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(): @@ -80,6 +82,72 @@ 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_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, 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 + 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(): obj = objective() config = {"objectives": [obj]} diff --git a/tests/harness/test_service_reference_evidence.py b/tests/harness/test_service_reference_evidence.py index 98c9bd33f..70e1f2d2b 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, } diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 008b28d97..2fcc63bed 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -656,7 +656,9 @@ def _inventory(root, prefix): **_inventory(files("inferrsi").joinpath("knowledge", "data"), "knowledge/data"), **_inventory(files("inferrsi").joinpath("resources", "repo_packs"), "resources/repo_packs"), } -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