@miadi/connector 0.1.37 → 0.1.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,7 @@ Call `get_capabilities` first. It names the signed-in person, their Miadi API ti
29
29
  - **Episode files.** `get_evidence` lists an episode's files; each text file Miadi can preview carries a `read_ref` (`miadi-chronicle://<n>/<path>`). `read_episode_file` (or `fetch` with that ref) returns the file's whole UTF-8 text, read as the person through Miadi's file door, so Miadi's audience and room rules apply. The answer names the episode, the path, the content type, the byte count and the sha256, and `verified` says whether the text received hashes to what Miadi read. Only md, txt, yaml, yml and json files up to 512 KiB are read. A traversal, absolute, hidden or encoded path is refused before any URL is built. A longer text comes in pages cut on character boundaries: pass `page.next` back, and the joined pages hash to `sha256`. Other kinds answer `unsupported`, a file over the limit `too_large`, a missing one `not_found`, a ceremony note below the write gate `forbidden`.
30
30
  - **One narrow grant.** A person with no Miadi API tier who holds `chronicle_foundations_read` (ticked by an admin under /admin → People → Additional permissions; admins hold it through their role) reaches `read_episode_file` for foundation documents only: `foundations/<topic>/*.md`, read through Miadi's `GET /api/chronicle/episodes/<ref>/foundations/<topic>/<file>.md`, which checks the permission on every read. Naming the episode alone lists them. Every other file and every other tool stays refused, and the permission gives no API tier. Unticking it refuses the next read. `get_capabilities` reports it under `foundation_read`, from Miadi's answer at that moment.
31
31
  - **Contributions** need Miadi's read tier and the `miadi:contribute` scope, chosen at sign-in. A record is moved on (`update_handoff`) only by its author or the write tier, and a request's receipt comes only from its decision. They append a record to the ledger and change nothing else, except `save_research`: it saves a report on the inquiry shelf as a new folder (the Markdown exactly as given, owner and visibility recorded, private by default), opens the folder's inquiry issue, and commits and pushes the folder in the shelf's repository. A long report is sent in parts (`part`, `parts`, `upload_id`) and saved when the last part arrives; the answer returns its bytes, sha256 and first and last lines.
32
+ - **Sharing a record.** A record's author shares it with a talking circle or one person by linking from it: `link_records` with `from` the record's id, `to` `miadi-circle:<circle id>` or the person's id, and `relation` `shared_with`. `share_withdrawn`, from the same record to the same reader, ends the share. Only the author's links count, and `link_records` refuses a share from anyone else. The record's page (`/records/<id>`) admits its author, the people and members of the circles it is shared with (their circles read from Miadi on every read), and the read tier, and it says how the reader was admitted. Miadi's `/research` lists what is shared with a person under Shared.
32
33
  - **Requests** append a record that waits for a decision. The answer gives an `approval_url`; Miadi's `/research` page offers the same decisions to a signed-in person with the write tier, and `show_decisions` shows them as cards inside the conversation (below). The person approves, approves with changes (their instructions are carried into what runs), sends it back for revision with instructions (`revision_requested`, nothing runs, `get_run_result` returns the instructions), or declines. Only the approval door runs a request, once, as that person; a second decision on the same request, at the same time or later, is refused:
33
34
  - a run becomes a brief in the factory queue, which the intake delivers to a session;
34
35
  - a work proposal starts its work the same way, as a brief written from the proposal;
@@ -47,7 +48,7 @@ The model that asked cannot approve its own request.
47
48
  A review is processed from the words of its video, so the connector acquires them itself, for a review made anywhere: the review service's own page, a manual edit, another client, or this connector's `create`.
48
49
 
49
50
  - **`ensure_review_transcript`** starts one job per review. It needs a person who may contribute and who holds Miadi's write tier or registered the video's source. It asks no transcript decision and needs no pasted text: processing a review already carries that authority. It never overwrites, never creates a version and never publishes.
50
- - **Order.** 1. The transcript the review service already holds is kept, read back and its digest recorded. 2. A source registered as withheld is held: nothing is read or stored until it is released. 3. The video's captions in its **spoken language** (the video's own `language`; YouTube auto-dubs a video into many languages and lists an `-orig` track for each dub, so the first `-orig` track is not taken, and a track in the wrong script is refused). 4. A transcription made on this host (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`, off until the operator enables it, one at a time, at most `MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES` minutes), only for a source its owner released. No model service is called and nothing costs money. 5. One `POST /api/reviews/{id}/transcript` with `overwrite: false` and the words' provenance. 6. A readback of the stored text, whose sha256 must match what was sent.
51
+ - **Order.** 1. The transcript the review service already holds is kept, read back and its digest recorded. 2. A source registered as withheld is held: nothing is read or stored until it is released. 3. The video's captions in its **spoken language** (the video's own `language`; YouTube auto-dubs a video into many languages and lists an `-orig` track for each dub, so the first `-orig` track is not taken, and a track in the wrong script is refused). 4. A transcription of the video's audio made on this host when the video has no usable caption track (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`, one at a time, at most `MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES` minutes). It runs for every review, because each job starts from an authority that covers processing it: the `review.created` fact, a person with the write tier or the source's registrant, or an approved mission. A withheld source is held before this step. Three attempts that produce no transcript end the job as `local_transcription_failed` with the last answer. On a host where it is off, the job keeps retrying and its failure names the operator. No model service is called and nothing costs money. 5. One `POST /api/reviews/{id}/transcript` with `overwrite: false` and the words' provenance. 6. A readback of the stored text, whose sha256 must match what was sent.
51
52
  - **Progress and failure.** The answer comes within about 20 seconds with the job's state and goes on if it needs longer. `review_transcript_status` (read-only; `verify: true` reads the transcript back now) says `unknown`, `absent`, `acquiring`, `stored`, `held` or `failed`, with the stages, the attempts, `next_attempt_at` and `give_up_at`, the digest and coverage of what is stored, and for a failure its code, the remedy and who can do it (`operator`, `source_owner`). Captions that YouTube has not made yet are tried every 15 minutes for three days. A job a restart interrupted resumes from its receipt; a held job resumes when its source is released.
52
53
  - **Links that need no card.** Every answer carries plain links: `status` (`/transcripts/<review id>`, a page that asks for a Miadi person token, or JSON with `Authorization: Bearer` and `?format=json`), `review`, `transcript_api` (the review service, with its token) and `job` (the job's record). `decision` is `null`: no decision stands between the request and the store. `review_lookup` and `review_versions` carry the same `transcript` state, and `show_decisions` and `get_run_result` answer with a line and a link for each request, so a client that draws no card still shows where things stand.
53
54
  - **Every review, however it was made.** The review service announces `review.created` for each review it creates (its site, its API, a Shortcut, this connector), built with `@miadi/hooks-core`'s `buildReviewCreatedEvent` and signed like its other factory webhooks. Miadi's `/api/factory/review-events` normalizes it, records it in the event ledger (`@miadi/hooks-gateway`, `MIADI_EVENTS_DIR`, default `/srv/miadi/events`) and hands it to this connector's inbox, `inbox/connector-transcripts/`. Every 15 seconds the connector takes up to three: it asks the review service for the review again, starts the review's transcript job (a review that already holds one stores nothing, a withheld source is held), records the fact as the job's authority, and moves the file to `done/` or, with the reason, to `rejected/`. A fact waits in the inbox while the connector is down or the review service cannot be asked.
@@ -112,13 +113,15 @@ Rollback: run the connector version before this one (`git checkout` of its `dist
112
113
 
113
114
  **Codex runs only on its requester's own choice (jgwill/Miadi#926).** The provider field is the caller's: the connector cannot read the chat, so `provider: "codex"` chooses nothing for the person. A run that names Codex is recorded, and its answer says it `needs_person_choice`. The approval page then shows no Approve button. Only the requester, signed in there with their own Miadi person token, can tick and send "Choose codex for this mission". That `provider_choice` record is bound to the request id, its version and its content hash, must be under 24 hours old when the request is approved, and covers that one mission. A revision makes it stale. A generic Approve, on the page or on a card, is refused as `provider_choice_required`, and so is a choice by any other person or by a service token. The requester can instead set their own policy at `/providers` so their requests may name Codex without a per-mission choice; that policy is theirs only and revisable. The check runs at request, revision, approval, and where the brief is written (approval and every rerun). The brief carries `provider_authorization` and `provider_choice` (or `provider_policy`), and the factory runner refuses to launch Codex for a connector brief without them. `request_authorized_run`, `revise_pending_request`, `mission_status`, `show_decisions` and `mission_model_preflight` show `provider_authorization`; after approval it is also in the request's `completion_receipt`, which `get_run_result` returns. A Codex launch without it is named on the mission and fails the preflight closed as `provider_not_authorized`. A brief the runner refuses goes to `queue/refused/` with its reason, and the request shows it. Other providers keep their regular policy, and nothing falls back to Codex. What this does not cover: anyone who can write `/srv/miadi/factory/queue` or the connector's state directory can forge a brief or a record (the folder's permissions are the boundary); a configured launcher that runs Codex behind a wrapper whose name does not say codex is trusted as configured; a brief to an existing session reaches only an idle Claude Code agent today, so it is not checked; and an agent that starts `codex` itself from inside its session is outside the connector's reach.
114
115
 
115
- **Which Claude Code model a run launches on.** `request_authorized_run` and `propose_work` may name a `model`, and that model is used. It must be on the host's permitted list, and a model named with any other provider is refused, so a model never moves a mission to a provider nobody chose. With none named, Jev chooses among the permitted models once, when the run is approved. It is sent the task type and criticality (`task_type`, `criticality`; default `implementation`, `normal`) and the candidates, never task text, a mission id or a repository name, and its choice authorizes nothing. If Jev has no key, is down, abstains, answers below the 0.8 floor or breaks the answer contract, the launch uses the configured Claude Code model, and the receipt's `fallback_reasons` says why. Jev knows these models only through the fit notes in `claude-models.ts`, which are the Factory's reading of Anthropic's descriptions and not a measurement: `implementation` fits Sonnet, `file_relevance` and normal `review` fit Opus, `architecture_refactor` and anything `security_critical` fit Fable. Its confidence is uncalibrated. A request that fills no `task_type` counts as `implementation`, so it goes to Sonnet even where Claude Code's own setting says Opus.
116
+ **Which Claude Code model a run launches on.** `request_authorized_run` and `propose_work` may name a `model`, and that model is used. It must be on the host's permitted list, and a model named with any other provider is refused, so a model never moves a mission to a provider nobody chose. With none named, Jev chooses among the permitted models once, when the run is approved. It is sent the task type and criticality (`task_type`, `criticality`; default `implementation`, `normal`) and the candidates, never task text, a mission id or a repository name, and its choice authorizes nothing. If Jev has no key, is down, abstains, answers below the 0.8 floor or breaks the answer contract, the launch uses the configured Claude Code model, and the receipt's `fallback_reasons` says why. Jev knows these models only through the fit notes in `claude-models.ts`, which are the Factory's reading of Anthropic's descriptions and not a measurement: `implementation` fits Sonnet, `file_relevance` and normal `review` fit Opus, `architecture_refactor` and anything `security_critical` fit Fable. Its confidence is uncalibrated. A request that fills no `task_type` counts as `implementation`, so it goes to Sonnet even where Claude Code's own setting says Opus; the draft review flags that absence (aspect S7), and the approval page and the receipt (`model_routing.labels`) say which label was a default and which the requester or the approver set.
117
+
118
+ **A floor, and the approver's fields.** A request may set `model_floor` (`opus`, `sonnet`, `haiku` or `fable`): the weakest model it may run on, for a floor its words set ("a high-reasoning review"). Models below it are offered to Jev as ineligible, so it chooses at or above the floor and reads no words; without Jev's choice the configured model launches, or the first permitted model at or above the floor when the configured one is below it. When no permitted model meets the floor, the approval page says so, offers only Approve with my changes, and a plain approve is refused as `model_floor_unmet`. A model named below the request's own floor is refused as `model_below_floor`. The draft review's S7 also flags words that set a model or a floor with no `model_floor` to carry them. A person approving with changes may set the model, the task type and the criticality in fields, on the approval page, on the card and in `decide_request`: a model they set launches with `model_source` `approver` and Jev is not asked, labels they set replace the request's in what Jev is sent, and the receipt keeps them as `routing_changes` and the replaced values as `model_routing.replaced`. Their instructions go to the agent and are not read for the model; the page says so before the click and the receipt says so after (`model_routing.instructions`). No reasoning effort is chosen: the seat starts at the `effortLevel` of Claude Code's settings on the host that opens it, and the receipt says so (`model_routing.effort`).
116
119
 
117
120
  A session already running keeps its model: Jev is not asked, and a named model fails the run rather than being ignored. A request recorded before this behaviour launches as it was approved. If Claude Code is missing or shows no sign-in when a run is approved, the run fails with no brief and can be run again. The brief carries `model` and `model_source`, and the factory runner passes `--model`; publish the runner first, because a runner older than 0.1.5 ignores it. `mission_status` shows the choice, its source, the flag, the model the session's own transcript says answered, read when asked, and whether they match. A mismatch or an old runner is a note, and nothing is re-run. A config directory is sign-in evidence only: only the transcript shows a launch worked.
118
121
 
119
122
  `factory.json` narrows the list and sets the fallback: `"claudeModels": ["opus", "sonnet"]`, `"claudeDefaultModel": "opus"`. Without them every model in `claude-models.ts` is permitted, and the fallback is the `model` in Claude Code's own settings. A list that leaves that setting out wins over it, and the fallback is then the first listed. A name goes on that list after a real answer shows it: `claude -p "Reply with OK." --model <name> --output-format json` names the model that answered under `modelUsage`, and an unknown name exits 1.
120
123
 
121
- `mission_model_preflight` (write tier) answers, for one mission, which provider and model fit its task type and criticality, and how that is known: contract `miadi.mission_model_preflight` v1, candidates with their configured default model, sign-in evidence (config directory only), quota `unknown`, policy eligibility, a review floor, and a recommendation or an abstention with reasons. Its `decider.source` is `static_fallback`, `jev` or `synthetic_fixture`. Jev is asked only with `consult_jev: true` and a key on the host; it is sent task type, criticality and candidates, never task text, mission id or repository, and its answer is advisory: uncalibrated, below 0.8 or outside the contract, the preflight abstains. A reported `launch` on another provider than the approved one answers `provider_mismatch` before anything is asked. It authorizes nothing. `bench/model-preflight-bench.mjs` compares the 0.1.12 baseline, the static preflight and Jev on synthetic scenarios; `bench/results/` keeps the runs.
124
+ `mission_model_preflight` (write tier) answers, for one mission, which provider and model fit its task type and criticality, and how that is known. Left out, the task type and criticality are the mission's own, as a launch reads them (the approver's fields, else the requester's, else the default), its floor applies, and `labels` says where each came from: contract `miadi.mission_model_preflight` v1, candidates with their configured default model, sign-in evidence (config directory only), quota `unknown`, policy eligibility, a review floor, and a recommendation or an abstention with reasons. Its `decider.source` is `static_fallback`, `jev` or `synthetic_fixture`. Jev is asked only with `consult_jev: true` and a key on the host; it is sent task type, criticality and candidates, never task text, mission id or repository, and its answer is advisory: uncalibrated, below 0.8 or outside the contract, the preflight abstains. A reported `launch` on another provider than the approved one answers `provider_mismatch` before anything is asked. It authorizes nothing. `bench/model-preflight-bench.mjs` compares the 0.1.12 baseline, the static preflight and Jev on synthetic scenarios; `bench/results/` keeps the runs.
122
125
 
123
126
  ### The mission standard
124
127
 
package/dist/approve.d.ts CHANGED
@@ -19,7 +19,7 @@ import { type RequestProjection } from "./request-state.js";
19
19
  import type { DraftReviewService } from "./draft-review.js";
20
20
  import { type RuntimeDeps } from "./runtime-steer.js";
21
21
  import { type TmuxLike } from "./steer.js";
22
- import { type ModelRoutingDeps } from "./claude-models.js";
22
+ import { type ApproverRouting, type ModelRoutingDeps } from "./claude-models.js";
23
23
  import { type FetchCaptions } from "./captions.js";
24
24
  import { type TranscriptJobIo } from "./transcript-job.js";
25
25
  import { type ProviderAuthorization } from "./provider-policy.js";
@@ -53,7 +53,7 @@ export interface ApprovalDeps {
53
53
  modelRouting?: ModelRoutingDeps;
54
54
  /** Reads a video's captions for an approved create; without it a create stores no transcript (tests, other embedders). */
55
55
  captions?: FetchCaptions;
56
- /** A transcription made on this host from the video's audio, tried for a released source whose captions are missing (jgwill/Miadi#995). */
56
+ /** A transcription made on this host from the video's audio, tried when the video has no captions (jgwill/Miadi#995). */
57
57
  localTranscription?: FetchCaptions;
58
58
  /** The event folder (`MIADI_EVENTS_DIR`, default /srv/miadi/events): the ledger of facts and this connector's inbox. Absent, no fact is taken or announced. */
59
59
  eventsDir?: string;
@@ -98,7 +98,28 @@ export declare function episodeReferences(record: ConnectorRecord): string[];
98
98
  export declare function sourceWithheld(records: ConnectorRecord[], videoId: unknown): boolean;
99
99
  /** What a transcript job needs from this connector: its ledger, the review service's transcript door and the readers. */
100
100
  export declare function transcriptJobIo(deps: Pick<ApprovalDeps, "config" | "ledger" | "fetchImpl" | "captions" | "localTranscription" | "log" | "eventsDir">): TranscriptJobIo;
101
- export declare function executeApproved(record: ConnectorRecord, approver: MiadiPerson, deps: ApprovalDeps, instructions?: string): Promise<Record<string, unknown>>;
101
+ /** Whether a mission's model is chosen by routing (a model named, or Jev's choice): only then do the approver's model fields apply. */
102
+ export declare function isClaudeRouted(r: ConnectorRecord): boolean;
103
+ export type ApproverRoutingCheck = {
104
+ routing?: ApproverRouting;
105
+ } | {
106
+ refusal: {
107
+ code: string;
108
+ message: string;
109
+ permitted?: string[];
110
+ };
111
+ };
112
+ /**
113
+ * The model fields a person sets when approving with changes, checked as a request's are: a model on the permitted
114
+ * list, a task type and criticality from their lists, and only on a mission whose model is routed on Claude Code
115
+ * (jgwill/Miadi#1029). Empty fields are no change.
116
+ */
117
+ export declare function approverRoutingOf(r: ConnectorRecord, fields: {
118
+ model?: unknown;
119
+ task_type?: unknown;
120
+ criticality?: unknown;
121
+ }, permitted: string[]): ApproverRoutingCheck;
122
+ export declare function executeApproved(record: ConnectorRecord, approver: MiadiPerson, deps: ApprovalDeps, instructions?: string, approverRouting?: ApproverRouting): Promise<Record<string, unknown>>;
102
123
  export declare function page(title: string, body: string): string;
103
124
  /**
104
125
  * Record a person's decision on a request and, when approved, run it once as
@@ -129,6 +150,9 @@ export declare class ProviderChoiceRequired extends Error {
129
150
  readonly authorization: ProviderAuthorization;
130
151
  constructor(authorization: ProviderAuthorization);
131
152
  }
153
+ /** An approval no permitted model can run: the request sets a floor none meets, and the approver named no model (jgwill/Miadi#1028). */
154
+ export declare class ModelFloorUnmet extends Error {
155
+ }
132
156
  /** What a decision answers: the state it left, its receipt, and `replayed` when it repeats a decision already taken. */
133
157
  export interface Decided {
134
158
  decision: NonNullable<ConnectorRecord["approval_state"]>;
@@ -151,6 +175,7 @@ export declare function approvalStateOf(choice: Decision): NonNullable<Connector
151
175
  */
152
176
  export declare function decide(r: ConnectorRecord, person: MiadiPerson, choice: Decision, deps: ApprovalDeps, opts: {
153
177
  instructions?: string;
178
+ routing?: ApproverRouting;
154
179
  note?: string;
155
180
  via: string;
156
181
  expectedVersion?: number;
@@ -193,7 +218,7 @@ export declare function consequenceOf(r: ConnectorRecord, authorization?: Provid
193
218
  steerable: boolean;
194
219
  basis: string;
195
220
  reason?: string;
196
- }): string;
221
+ }, floorUnmet?: boolean): string;
197
222
  export declare function registerApprovalRoutes(app: Express, deps: ApprovalDeps): void;
198
223
  /**
199
224
  * The page a person named in a consent request decides on. Their link is the door: a person who never
package/dist/approve.js CHANGED
@@ -19,6 +19,7 @@ import { DEFAULT_DECISION_WAIT_MS } from "./config.js";
19
19
  import { MiadiError } from "./miadi.js";
20
20
  import { MiadiUnavailable } from "./people.js";
21
21
  import { current, newRecordId } from "./records.js";
22
+ import { recordAccess, recordSharedWithACircle } from "./record-shares.js";
22
23
  import { APPROVABLE, projectRequest } from "./request-state.js";
23
24
  import { factoryDir, runBriefFile, readQueueState } from "./queue-state.js";
24
25
  import { factoryLedgerPath, readFactoryReceipts, receiptsForRecord } from "./factory-receipt.js";
@@ -26,7 +27,8 @@ import { readSteerDelivery } from "./runtime-steer.js";
26
27
  import { adapterOfRoute, readFactoryConfig } from "./steering-adapters.js";
27
28
  import { steerAttempts, steerSession, tmuxAdapter } from "./steer.js";
28
29
  import { contentHash, versionOf } from "./revisions.js";
29
- import { modelAttributes, routeModel } from "./claude-models.js";
30
+ import { claudeModelConfig, floorOf, floorRefusal, isPermittedModel, JEV_WITHIN_CLAUDE, labelsOf, meetsFloor, modelAttributes, MODEL_NAME, modelsMeetingFloor, routeModel, } from "./claude-models.js";
31
+ import { CRITICALITIES, TASK_TYPES } from "./model-preflight.js";
30
32
  import { TRANSCRIPT_RETRY_MS, transcriptStep } from "./captions.js";
31
33
  import { reviewTranscriptService, settleTranscriptJobs } from "./transcript-job.js";
32
34
  import { settleTranscriptRequests } from "./transcript-intake.js";
@@ -264,7 +266,46 @@ async function videoOfReview(deps, reviewId) {
264
266
  return null;
265
267
  }
266
268
  }
267
- export async function executeApproved(record, approver, deps, instructions) {
269
+ /** Whether a mission's model is chosen by routing (a model named, or Jev's choice): only then do the approver's model fields apply. */
270
+ export function isClaudeRouted(r) {
271
+ const b = r.body;
272
+ return (r.kind === "run_request" || r.kind === "work_proposal") && ((typeof b.model === "string" && Boolean(b.model)) || b.model_routing === JEV_WITHIN_CLAUDE);
273
+ }
274
+ /**
275
+ * The model fields a person sets when approving with changes, checked as a request's are: a model on the permitted
276
+ * list, a task type and criticality from their lists, and only on a mission whose model is routed on Claude Code
277
+ * (jgwill/Miadi#1029). Empty fields are no change.
278
+ */
279
+ export function approverRoutingOf(r, fields, permitted) {
280
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
281
+ const model = text(fields.model);
282
+ const task_type = text(fields.task_type);
283
+ const criticality = text(fields.criticality);
284
+ if (!model && !task_type && !criticality)
285
+ return {};
286
+ if (!isClaudeRouted(r)) {
287
+ const provider = String(r.body.resolved_provider ?? r.body.provider ?? "another provider");
288
+ return { refusal: { code: "model_provider_mismatch", message: `This mission runs on ${provider}, so a Claude Code model, task type or criticality cannot be set for it. Nothing was decided.` } };
289
+ }
290
+ if (model && (!MODEL_NAME.test(model) || !isPermittedModel(model, permitted))) {
291
+ return { refusal: { code: "model_not_permitted", message: `${model} is not a permitted Claude Code model on this host (${permitted.join(", ")}). Nothing was decided.`, permitted } };
292
+ }
293
+ if (task_type && !TASK_TYPES.includes(task_type))
294
+ return { refusal: { code: "invalid_request", message: `${task_type} is not a task type (${TASK_TYPES.join(", ")}). Nothing was decided.` } };
295
+ if (criticality && !CRITICALITIES.includes(criticality))
296
+ return { refusal: { code: "invalid_request", message: `${criticality} is not a criticality (${CRITICALITIES.join(", ")}). Nothing was decided.` } };
297
+ const named = r.body.model;
298
+ if (!model && typeof named === "string" && named) {
299
+ return { refusal: { code: "labels_take_no_part", message: `This mission names its model (${named}), so a task type or criticality would change nothing. Set the model instead. Nothing was decided.` } };
300
+ }
301
+ return { routing: { ...(model ? { model } : {}), ...(task_type ? { task_type: task_type } : {}), ...(criticality ? { criticality: criticality } : {}) } };
302
+ }
303
+ /** The model fields a decision carries, as recorded in its receipt; a rerun runs with them again. */
304
+ const routingOfReceipt = (receipt) => {
305
+ const c = receipt.routing_changes;
306
+ return c && typeof c === "object" && Object.keys(c).length ? c : undefined;
307
+ };
308
+ export async function executeApproved(record, approver, deps, instructions, approverRouting) {
268
309
  const f = deps.fetchImpl ?? fetch;
269
310
  const b = record.body;
270
311
  const reviewCall = (method, path, payload) => callReview(deps, method, path, payload);
@@ -286,10 +327,11 @@ export async function executeApproved(record, approver, deps, instructions) {
286
327
  }
287
328
  // A session already running keeps its model: a named one cannot be honoured, and Jev is not asked (jgwill/Miadi#943).
288
329
  const existingSession = record.kind === "run_request" && typeof b.session === "string" && sessions.includes(b.session);
289
- if (existingSession && typeof b.model === "string" && b.model) {
290
- return { outcome: "failed", message: `No brief was written. Session ${b.session} is already running on its own model, so ${b.model} cannot apply. Run it again once that session has ended, or make a new request with another session name.` };
330
+ const named = approverRouting?.model ?? (typeof b.model === "string" && b.model ? b.model : null);
331
+ if (existingSession && named) {
332
+ return { outcome: "failed", message: `No brief was written. Session ${b.session} is already running on its own model, so ${named} cannot apply. Run it again once that session has ended, or make a new request with another session name.` };
291
333
  }
292
- const routing = await routeModel(record, { existingSession }, { factoryDir: deps.factoryDir, ...deps.modelRouting });
334
+ const routing = await routeModel(record, { existingSession, ...(approverRouting ? { approver: approverRouting } : {}), instructions: Boolean(instructions) }, { factoryDir: deps.factoryDir, ...deps.modelRouting });
293
335
  if (routing?.source === "unavailable") {
294
336
  return { outcome: "failed", model_routing: routing, message: `No brief was written. ${routing.why}, and no other provider stands in for it. Run it again once it is back.` };
295
337
  }
@@ -523,6 +565,17 @@ fieldset{border:1px solid var(--line);border-radius:.4rem;margin:1rem 0;padding:
523
565
  fieldset legend{float:left;width:100%;padding:0;margin-bottom:.3rem;font-size:.95rem}
524
566
  fieldset label{clear:both;display:flex;align-items:flex-start;gap:.5rem;min-height:34px;margin:.45rem 0;font-weight:400}
525
567
  input[type=radio]{accent-color:var(--accent);flex:0 0 auto;margin:.3rem 0 0}
568
+ select{width:100%;min-width:0;max-width:100%;min-height:34px;box-sizing:border-box;padding:.4rem .5rem;border:1px solid var(--line);border-radius:.4rem;background:var(--bg);color:var(--fg);font:inherit}
569
+ select:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
570
+ .model-fields{margin-top:.6rem}
571
+ .model-fields .pair{display:grid;grid-template-columns:7.5rem minmax(0,22rem);gap:.5rem;align-items:center;margin:.45rem 0}
572
+ .model-fields .pair label{clear:both;margin:0;min-height:0;font-weight:400}
573
+ .model-fields .pair>*{min-width:0}
574
+ .gv{display:grid;grid-template-columns:1rem minmax(0,1fr);gap:.4rem;align-items:start}
575
+ .gv .glyph{margin-top:.3rem}
576
+ .gv.stopped .glyph{color:var(--err,#b00020)}
577
+ .hint{margin:.1rem 0 .4rem;font-size:.9rem}
578
+ @media (max-width:480px){.model-fields .pair{grid-template-columns:minmax(0,1fr);gap:.2rem}}
526
579
  .code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}
527
580
  .glyph{margin-top:.25rem;color:var(--muted)}
528
581
  .wordsLabel{margin-bottom:.1rem}
@@ -584,6 +637,9 @@ export class ProviderChoiceRequired extends Error {
584
637
  this.authorization = authorization;
585
638
  }
586
639
  }
640
+ /** An approval no permitted model can run: the request sets a floor none meets, and the approver named no model (jgwill/Miadi#1028). */
641
+ export class ModelFloorUnmet extends Error {
642
+ }
587
643
  /** The decisions being recorded now, by request id: one at a time per request, in this process. */
588
644
  const deciding = new Map();
589
645
  /** Whether a decision on this request is being recorded now, its run may still be going. */
@@ -600,7 +656,11 @@ const APPROVAL_OF = {
600
656
  export function approvalStateOf(choice) {
601
657
  return APPROVAL_OF[choice];
602
658
  }
603
- const sameDecision = (a, b) => a.choice === b.choice && String(a.instructions ?? "").trim() === String(b.instructions ?? "").trim();
659
+ const routingKey = (r) => {
660
+ const o = (r ?? {});
661
+ return ["model", "task_type", "criticality"].map((k) => String(o[k] ?? "")).join("|");
662
+ };
663
+ const sameDecision = (a, b) => a.choice === b.choice && String(a.instructions ?? "").trim() === String(b.instructions ?? "").trim() && routingKey(a.routing) === routingKey(b.routing);
604
664
  /**
605
665
  * Record a person's decision once. The page and the card (or two cards, or a host
606
666
  * that retries a call it gave up waiting on) may send it more than once:
@@ -613,10 +673,10 @@ export async function decide(r, person, choice, deps, opts) {
613
673
  // Checked again here, with no await between the check and the claim: the
614
674
  // page and the card (or two cards) may decide the same request at once, and
615
675
  // a revision may land between reading a version and deciding it (#919).
616
- const asked = { choice, instructions: opts.instructions };
676
+ const asked = { choice, instructions: opts.instructions, routing: opts.routing };
617
677
  const inflight = deciding.get(r.id);
618
678
  if (inflight) {
619
- if (inflight.promise && inflight.choice !== "rerun" && sameDecision({ choice: inflight.choice, instructions: inflight.instructions }, asked)) {
679
+ if (inflight.promise && inflight.choice !== "rerun" && sameDecision({ choice: inflight.choice, instructions: inflight.instructions, routing: inflight.routing }, asked)) {
620
680
  logDecision(deps, { phase: "replay", record: r.id, correlation: inflight.correlation, via: opts.via, choice, while: "recording" });
621
681
  return { ...(await inflight.promise), replayed: true };
622
682
  }
@@ -632,7 +692,7 @@ export async function decide(r, person, choice, deps, opts) {
632
692
  if (live.approval_state !== "awaiting_approval") {
633
693
  const prior = (live.completion_receipt ?? {});
634
694
  const priorVersion = typeof prior.version === "number" ? prior.version : 1;
635
- if (typeof prior.decision === "string" && sameDecision({ choice: prior.decision, instructions: prior.instructions }, asked) && priorVersion === decidedVersion) {
695
+ if (typeof prior.decision === "string" && sameDecision({ choice: prior.decision, instructions: prior.instructions, routing: prior.routing_changes }, asked) && priorVersion === decidedVersion) {
636
696
  logDecision(deps, { phase: "replay", record: r.id, via: opts.via, choice, while: "recorded", state: live.state });
637
697
  return { decision: live.approval_state, state: live.state, receipt: prior, replayed: true };
638
698
  }
@@ -649,6 +709,14 @@ export async function decide(r, person, choice, deps, opts) {
649
709
  throw new ProviderChoiceRequired(authorization);
650
710
  }
651
711
  }
712
+ // A floor no permitted model meets launches nothing: refused before anything is recorded, so it still awaits a decision (jgwill/Miadi#1028).
713
+ if (approvalStateOf(choice) === "approved") {
714
+ const refused = floorRefusal(live, opts.routing, claudeModelConfig(deps.factoryDir ?? factoryDir(), deps.modelRouting?.modelOf));
715
+ if (refused) {
716
+ logDecision(deps, { phase: "model_floor_unmet", record: r.id, via: opts.via, choice });
717
+ throw new ModelFloorUnmet(refused);
718
+ }
719
+ }
652
720
  const entry = { ...asked, correlation: randomUUID(), started: Date.now() };
653
721
  deciding.set(r.id, entry);
654
722
  entry.promise = decideOnce(live, person, choice, deps, { ...opts, correlation: entry.correlation, started: entry.started });
@@ -819,11 +887,13 @@ export async function rerun(r, person, deps, opts) {
819
887
  try {
820
888
  const prior = (live.completion_receipt ?? {});
821
889
  const instructions = typeof prior.instructions === "string" ? prior.instructions : undefined;
890
+ const routing = routingOfReceipt(prior);
822
891
  let receipt = {
823
892
  decided_by: prior.decided_by,
824
893
  decided_at: prior.decided_at,
825
894
  decision: prior.decision,
826
895
  ...(instructions ? { instructions } : {}),
896
+ ...(routing ? { routing_changes: routing } : {}),
827
897
  rerun_by: { person_id: person.id, name: person.name },
828
898
  rerun_at: new Date().toISOString(),
829
899
  via: opts.via,
@@ -831,7 +901,7 @@ export async function rerun(r, person, deps, opts) {
831
901
  };
832
902
  let state = "completed";
833
903
  try {
834
- const outcome = await executeApproved(live, person, deps, instructions);
904
+ const outcome = await executeApproved(live, person, deps, instructions, routing);
835
905
  receipt = { ...receipt, ...outcome };
836
906
  if (outcome.outcome === "failed")
837
907
  state = "blocked";
@@ -862,7 +932,7 @@ export async function rerun(r, person, deps, opts) {
862
932
  }
863
933
  }
864
934
  async function decideOnce(r, person, choice, deps, opts) {
865
- const { instructions } = opts;
935
+ const { instructions, routing } = opts;
866
936
  const decision = approvalStateOf(choice);
867
937
  logDecision(deps, { phase: "start", record: r.id, kind: r.kind, correlation: opts.correlation, via: opts.via, choice, version: versionOf(r) });
868
938
  let receipt = {
@@ -874,6 +944,8 @@ async function decideOnce(r, person, choice, deps, opts) {
874
944
  content_hash: contentHash(r),
875
945
  via: opts.via,
876
946
  ...(instructions ? { instructions } : {}),
947
+ // The model fields the approver set: they take part in the choice, and a rerun runs with them (jgwill/Miadi#1029).
948
+ ...(routing && Object.keys(routing).length ? { routing_changes: routing } : {}),
877
949
  note: opts.note,
878
950
  correlation: opts.correlation,
879
951
  };
@@ -896,12 +968,12 @@ async function decideOnce(r, person, choice, deps, opts) {
896
968
  approval_state: decision,
897
969
  state: "in_progress",
898
970
  completion_receipt: { ...receipt, outcome: "running", started_at: new Date(opts.started).toISOString() },
899
- body: { decision: choice, ...(instructions ? { instructions } : {}) },
971
+ body: { decision: choice, ...(instructions ? { instructions } : {}), ...(routing && Object.keys(routing).length ? { routing_changes: routing } : {}) },
900
972
  });
901
973
  logDecision(deps, { phase: "running", record: r.id, correlation: opts.correlation, ms: Date.now() - opts.started });
902
974
  }
903
975
  try {
904
- const outcome = await executeApproved(r, person, deps, instructions);
976
+ const outcome = await executeApproved(r, person, deps, instructions, routing);
905
977
  receipt = { ...receipt, ...outcome };
906
978
  if (outcome.outcome === "failed")
907
979
  state = "blocked";
@@ -925,7 +997,7 @@ async function decideOnce(r, person, choice, deps, opts) {
925
997
  state,
926
998
  ...(decision === "revision_requested" ? { next_action: `Revise it in place with revise_pending_request (request_id ${r.id}, expected_version ${versionOf(r)}).` } : {}),
927
999
  completion_receipt: receipt,
928
- body: { decision: choice, ...(instructions ? { instructions } : {}) },
1000
+ body: { decision: choice, ...(instructions ? { instructions } : {}), ...(routing && Object.keys(routing).length ? { routing_changes: routing } : {}) },
929
1001
  });
930
1002
  logDecision(deps, {
931
1003
  phase: "done",
@@ -942,10 +1014,24 @@ async function decideOnce(r, person, choice, deps, opts) {
942
1014
  export function isApprovable(r) {
943
1015
  return Boolean(r && APPROVABLE.has(r.kind));
944
1016
  }
945
- const modelWords = (b) => (typeof b.model === "string" && b.model ? ` on ${b.model}` : b.model_routing ? " on the model Jev chooses" : "");
1017
+ /** The model in one clause: a named one, or Jev's choice with the labels it reads and whether each is a default (jgwill/Miadi#1028). */
1018
+ function modelWords(b) {
1019
+ if (typeof b.model === "string" && b.model)
1020
+ return ` on ${b.model}`;
1021
+ if (!b.model_routing)
1022
+ return "";
1023
+ const t = labelsOf(b);
1024
+ const d = (s) => (s === "default" ? " (the default)" : "");
1025
+ const floor = floorOf(b);
1026
+ return ` on the model Jev chooses for task type ${t.type}${d(t.labels.task_type)} and criticality ${t.criticality}${d(t.labels.criticality)}${floor ? `, at or above ${floor}` : ""}`;
1027
+ }
946
1028
  /** What approving a request does, in one sentence, for the card a person decides on. */
947
- export function consequenceOf(r, authorization, records = [], steering) {
1029
+ export function consequenceOf(r, authorization, records = [], steering, floorUnmet = false) {
948
1030
  const b = r.body;
1031
+ // A floor no permitted model meets: the first thing read is that approving as requested is refused (jgwill/Miadi#1028).
1032
+ if (floorUnmet && (r.kind === "run_request" || r.kind === "work_proposal")) {
1033
+ return `Approving as requested is refused: no permitted Claude Code model meets the floor this request sets (${String(b.model_floor)}). Approving with your changes runs it on the model you name.`;
1034
+ }
949
1035
  switch (r.kind) {
950
1036
  case "run_request":
951
1037
  return authorization && !authorization.authorized
@@ -1092,18 +1178,29 @@ export function registerApprovalRoutes(app, deps) {
1092
1178
  const choice = DECISIONS.includes(String(body.decision)) ? body.decision : "decline";
1093
1179
  const instructions = String(body.instructions ?? "").trim().slice(0, 20000) || undefined;
1094
1180
  const via = String(body.via ?? "approval-page").slice(0, 60);
1181
+ // The model fields take part in the choice; they are a change, so they go with Approve with my changes (jgwill/Miadi#1029).
1182
+ const fieldsCheck = approverRoutingOf(r, { model: body.model, task_type: body.task_type, criticality: body.criticality }, claudeModelConfig(deps.factoryDir ?? factoryDir(), deps.modelRouting?.modelOf).permitted);
1183
+ // A refused form comes back as it was sent: the words and the fields stay (critic U2).
1184
+ const kept = { instructions, model: body.model, task_type: body.task_type, criticality: body.criticality };
1185
+ if ("refusal" in fieldsCheck && (choice === "approve" || choice === "approve_with_changes"))
1186
+ return void res.status(400).type("html").send(approvePage(deps, r, { token, error: fieldsCheck.refusal.message, kept }));
1187
+ const routing = "routing" in fieldsCheck && choice === "approve_with_changes" ? fieldsCheck.routing : undefined;
1188
+ if ("routing" in fieldsCheck && fieldsCheck.routing && choice === "approve") {
1189
+ return void res.status(400).type("html").send(approvePage(deps, r, { token, error: "A model field changes the request: press Approve with my changes to apply it, or set the fields back to Keep.", kept }));
1190
+ }
1095
1191
  // Only a decision that would be recorded now needs its instructions; a form sent again after it was recorded is answered below (#924).
1096
- if (r.approval_state === "awaiting_approval" && !isBeingDecided(r.id) && (choice === "approve_with_changes" || choice === "request_revision") && !instructions) {
1192
+ if (r.approval_state === "awaiting_approval" && !isBeingDecided(r.id) && ((choice === "approve_with_changes" && !routing) || choice === "request_revision") && !instructions) {
1097
1193
  return void res
1098
1194
  .status(400)
1099
1195
  .type("html")
1100
- .send(approvePage(deps, r, { token, error: choice === "request_revision" ? "Say what to revise." : "Write the changes to apply." }));
1196
+ .send(approvePage(deps, r, { token, error: choice === "request_revision" ? "Say what to revise." : "Write the changes to apply, or set a model field.", kept }));
1101
1197
  }
1102
1198
  let decided;
1103
1199
  try {
1104
1200
  const shown = Number(body.version);
1105
1201
  const running = decide(r, person, choice, deps, {
1106
1202
  instructions,
1203
+ ...(routing ? { routing } : {}),
1107
1204
  note: body.note || undefined,
1108
1205
  via,
1109
1206
  ...(Number.isInteger(shown) && shown >= 1 ? { expectedVersion: shown } : {}),
@@ -1124,6 +1221,8 @@ export function registerApprovalRoutes(app, deps) {
1124
1221
  }
1125
1222
  if (error instanceof StaleVersion)
1126
1223
  return void res.status(409).type("html").send(approvePage(deps, find(r.id), { token, error: error.message }));
1224
+ if (error instanceof ModelFloorUnmet)
1225
+ return void res.status(409).type("html").send(approvePage(deps, find(r.id), { token, error: error.message, kept }));
1127
1226
  if (error instanceof AlreadyDecided)
1128
1227
  return void res.status(409).type("html").send(approvePage(deps, find(r.id), { error: error.message }));
1129
1228
  throw error;
@@ -1144,7 +1243,8 @@ export function registerApprovalRoutes(app, deps) {
1144
1243
  const again = replayed ? "<p>This decision was already recorded. Nothing ran again; here is where it stands.</p>" : "";
1145
1244
  res.type("html").send(page("Recorded", `<h1>${heading}</h1>${again}${summary(find(r.id))}${projectionBlock(p, receipt)}${p?.stage === "recording" ? refreshForm(token) : ""}`));
1146
1245
  });
1147
- // A record's own page, for citations in ChatGPT: its author and anyone with Miadi's read tier may read it.
1246
+ // A record's own page, for citations in ChatGPT and for a click on its id: its author, the people and the
1247
+ // talking circles its author shared it with, and anyone with Miadi's read tier may read it (jgwill/Miadi#1005).
1148
1248
  app.get("/records/:id", (req, res) => {
1149
1249
  res.type("html").send(page("Miadi record", recordForm(String(req.params.id))));
1150
1250
  });
@@ -1166,10 +1266,26 @@ export function registerApprovalRoutes(app, deps) {
1166
1266
  if (!canReadReading(r, current(deps.ledger.all()), person)) {
1167
1267
  return void res.status(403).type("html").send(page("Miadi record", recordForm(String(req.params.id), "This source and its reading are private to the source owner and factory operators.")));
1168
1268
  }
1169
- if (!person.api_tier && r.actor.person_id !== person.id) {
1170
- return void res.status(403).type("html").send(page("Miadi record", recordForm(String(req.params.id), `Reading records needs Miadi's read tier; ${person.name} has none.`)));
1269
+ const ledger = current(deps.ledger.all());
1270
+ let circles;
1271
+ // The reader's circles are read only when a circle could admit them: the author and the read tier need none.
1272
+ if (r.actor.person_id !== person.id && !person.api_tier && recordSharedWithACircle(r, ledger)) {
1273
+ try {
1274
+ const b = (await deps.miadi.get(String((req.body ?? {}).person_token ?? "").trim(), "/api/circles"));
1275
+ circles = (b?.circles ?? []).filter((c) => c?.member === true && typeof c.id === "string").map((c) => c.id);
1276
+ }
1277
+ catch {
1278
+ return void res.status(503).type("html").send(page("Miadi record", recordForm(String(req.params.id), "Your talking circles could not be read from Miadi, so whether this record reaches you through one cannot be decided now. Try again in a minute.")));
1279
+ }
1280
+ }
1281
+ const access = recordAccess(r, ledger, { id: person.id, api_tier: person.api_tier, circles });
1282
+ if (!access) {
1283
+ return void res.status(403).type("html").send(page("Miadi record", recordForm(String(req.params.id), `This record is read by its author, by the people and circles its author shares it with, and by Miadi's read tier; ${person.name} is none of these.`)));
1171
1284
  }
1172
- res.type("html").send(page("Miadi record", `<h1>${escapeHtml(r.kind)}</h1>${summary(r)}`));
1285
+ const reached = access.as === "shared"
1286
+ ? `<p>${access.routes.map((s) => escapeHtml(s.circle ? `Shared with the circle ${s.circle} by ${s.by}` : `Shared with you by ${s.by}`)).join("<br>")}</p>`
1287
+ : "";
1288
+ res.type("html").send(page("Miadi record", `<h1>${escapeHtml(r.kind)}</h1>${reached}${summary(r)}`));
1173
1289
  });
1174
1290
  }
1175
1291
  /**
@@ -1494,6 +1610,57 @@ ${canAnswer && open.some((f) => f.settled_by === "drafter") ? `<p class="muted">
1494
1610
  ${canAnswer && open.length ? `<p class="muted">Approving as it stands starts the session, and the worker reads these questions with the task.</p>` : ""}
1495
1611
  </section>`;
1496
1612
  }
1613
+ const CPU_PATHS = `<path d="M12 20v2"/><path d="M12 2v2"/><path d="M17 20v2"/><path d="M17 2v2"/><path d="M2 12h2"/><path d="M2 17h2"/><path d="M2 7h2"/><path d="M20 12h2"/><path d="M20 17h2"/><path d="M20 7h2"/><path d="M7 20v2"/><path d="M7 2v2"/><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="8" y="8" width="8" height="8" rx="1"/>`;
1614
+ const SET_BY = { requester: "set by the requester", approver: "set by the approver", default: "the default: the request sets none" };
1615
+ /**
1616
+ * Which model a mission runs on and what it is chosen from, before the click: the floor and what meets it, the labels
1617
+ * and who set each, that effort is not chosen, and that instructions do not choose the model (jgwill/Miadi#1028, #1029).
1618
+ * Deciding, the fields to change it sit in the same section, inside the form.
1619
+ */
1620
+ function modelBlock(r, deps, deciding, kept = {}) {
1621
+ if (!isClaudeRouted(r))
1622
+ return "";
1623
+ const b = r.body;
1624
+ const config = claudeModelConfig(deps.factoryDir ?? factoryDir(), deps.modelRouting?.modelOf);
1625
+ const floor = floorOf(b);
1626
+ const meeting = floor ? modelsMeetingFloor(config, floor) : [];
1627
+ const named = typeof b.model === "string" && b.model ? b.model : null;
1628
+ const unmet = Boolean(floor && !meeting.length && !named);
1629
+ const t = labelsOf(b);
1630
+ const valued = (label, paths, text, cls = "") => `<span class="gv${cls}">${glyph(label, paths)}<span>${escapeHtml(text)}</span></span>`;
1631
+ const rows = [
1632
+ `<dt>Model</dt><dd>${named
1633
+ ? valued("Named", CIRCLE_CHECK_PATHS, `${named}, named by the requester; Jev is not asked`)
1634
+ : unmet
1635
+ ? valued("Refused", TRIANGLE_ALERT_PATHS, "none", " stopped")
1636
+ : valued("Awaiting the decision", DASHED_PATHS, `chosen by Jev when it is approved, among ${(floor ? meeting : config.permitted).join(", ")}`)}</dd>`,
1637
+ ];
1638
+ if (floor)
1639
+ rows.push(`<dt>Floor</dt><dd>${escapeHtml(floor)}, set by the requester${meeting.length ? `; met by ${escapeHtml(meeting.join(", "))}` : ""}</dd>`);
1640
+ if (!named) {
1641
+ rows.push(`<dt>Task type</dt><dd>${escapeHtml(t.type)} (${SET_BY[t.labels.task_type]})</dd>`);
1642
+ rows.push(`<dt>Criticality</dt><dd>${escapeHtml(t.criticality)} (${SET_BY[t.labels.criticality]})</dd>`);
1643
+ }
1644
+ rows.push(`<dt>Effort</dt><dd>not chosen here: the seat starts at Claude Code's own effort setting on the host that opens it</dd>`);
1645
+ const refused = unmet
1646
+ ? `<p class="state stopped">${glyph("Refused", TRIANGLE_ALERT_PATHS)}<span>No permitted model meets the floor (${escapeHtml(floor)}). Approving as requested is refused; name a model below and press Approve with my changes.</span></p>`
1647
+ : "";
1648
+ const words = deciding
1649
+ ? "What you write under Instructions goes to the agent and does not choose the model. To change the model, set it here and press Approve with my changes."
1650
+ : "What the approver writes as instructions goes to the agent and does not choose the model; only the model fields do.";
1651
+ let fields = "";
1652
+ if (deciding) {
1653
+ const option = (value, chosen, note = "") => `<option value="${escapeHtml(value)}"${chosen === value ? " selected" : ""}>${escapeHtml(value + note)}</option>`;
1654
+ const select = (id, name, label, keep, values, chosen, noteOf = () => "") => `<div class="pair"><label for="${id}">${label}</label><select id="${id}" name="${name}"><option value="">${escapeHtml(keep)}</option>${values.map((v) => option(v, chosen, noteOf(v))).join("")}</select></div>`;
1655
+ const below = (v) => (floor && !meetsFloor(v, floor) ? " (below the floor)" : "");
1656
+ fields = `<div class="model-fields" role="group" aria-label="Change the model">
1657
+ ${select("m", "model", "Model", named ? `Keep: ${named}` : unmet ? "Choose a model" : "Keep: Jev chooses", config.permitted, kept.model, below)}
1658
+ ${named ? "" : select("tt", "task_type", "Task type", `Keep: ${t.type}${t.labels.task_type === "default" ? " (default)" : ""}`, TASK_TYPES, kept.task_type)}
1659
+ ${named ? "" : select("cr", "criticality", "Criticality", `Keep: ${t.criticality}${t.labels.criticality === "default" ? " (default)" : ""}`, CRITICALITIES, kept.criticality)}
1660
+ </div>`;
1661
+ }
1662
+ return `<section class="standard" aria-label="The model"><h2>The model</h2>${refused}<dl>${rows.join("")}</dl>${stateLine("Instructions do not choose the model", CPU_PATHS, escapeHtml(words))}${fields}</section>`;
1663
+ }
1497
1664
  const FILE_PLUS_PATHS = `<path d="M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="M14 19h6"/><path d="M17 16v6"/>`;
1498
1665
  /**
1499
1666
  * What approving does, then what declining does. An ending that files capability holdings in an episode says so on a line
@@ -1514,6 +1681,8 @@ function approvePage(deps, r, o = {}) {
1514
1681
  // Freshness binds a decision still to come; a decided run shows the authorization it holds (#926 review R1).
1515
1682
  const authorization = r.kind === "run_request" ? authorizeProvider(r, deps.ledger.all(), { requireFresh: open }) : undefined;
1516
1683
  const blocked = Boolean(authorization && !authorization.authorized);
1684
+ // A floor no permitted model meets: Approve and run would be refused, so only Approve with my changes (naming a model) is offered (jgwill/Miadi#1028).
1685
+ const floorUnmetHere = open && Boolean(floorRefusal(r, undefined, claudeModelConfig(deps.factoryDir ?? factoryDir(), deps.modelRouting?.modelOf)));
1517
1686
  // Signed in and able to decide: the decision comes before the record's details, and no line says it waits for someone else.
1518
1687
  const asksSomeone = r.kind === "participant_consent_request";
1519
1688
  const canDecideHere = Boolean(actionable && o.token && !asksSomeone);
@@ -1533,27 +1702,30 @@ ${projectionBlock(projectionOf(r, deps), open ? undefined : r.completion_receipt
1533
1702
  ${canDecideHere ? `<p>You are signed in. Nothing is approved until you press a button below.</p>` : ""}
1534
1703
  ${asksSomeone && open && o.token && deps.consentLink ? consentMailSection(r, deps) : ""}
1535
1704
  ${asksSomeone && open && (o.token || o.chooserToken) && deps.consentLink ? `<p><strong>The link to send ${escapeHtml(String(r.body.decider_name))}:</strong><br><a href="${escapeHtml(deps.consentLink(r.id))}" rel="noreferrer">${escapeHtml(deps.consentLink(r.id))}</a></p>` : ""}
1536
- ${actionable ? effectParagraphs(consequenceOf(r, authorization, current(deps.ledger.all()))) : ""}
1705
+ ${actionable ? effectParagraphs(consequenceOf(r, authorization, current(deps.ledger.all()), undefined, floorUnmetHere)) : ""}
1537
1706
  ${runSteeringLine(r, authorization?.provider ?? undefined, deps)}
1538
1707
  ${capabilitiesSection(r, deps.config.miadiPublicUrl)}
1539
1708
  ${canDecideHere && r.intention ? `<p><strong>Intention:</strong> ${escapeHtml(r.intention)}</p>` : ""}
1540
1709
  ${authorization ? providerSection(r, authorization, actionable ? o.chooserToken : undefined) : ""}
1710
+ ${open && o.token && !(canDecideHere && !blocked) ? modelBlock(r, deps, false) : ""}
1541
1711
  ${canDecideHere ? draftReviewSection(r, deps.draftReview?.stored(r), !blocked) : ""}
1542
- ${o.error ? `<p class="err" role="alert">${escapeHtml(o.error)}</p>` : ""}
1712
+ ${o.error ? `<p class="err" role="alert" id="decide">${escapeHtml(o.error)}</p>` : ""}
1543
1713
  ${asksSomeone && open && o.token && deps.consentLink && r.body.decider_person_id && !consentMailSent(deps, r.id)
1544
1714
  ? `<form method="post"><input type="hidden" name="person_token" value="${escapeHtml(o.token)}"><div class="row"><button class="primary" type="submit" name="decision" value="send_consent_mail">Send this email</button></div></form>`
1545
1715
  : ""}
1546
1716
  ${canDecideHere
1547
- ? `<form method="post">
1717
+ ? `<form method="post" action="#decide">
1548
1718
  <input type="hidden" name="person_token" value="${escapeHtml(o.token)}">
1549
1719
  <input type="hidden" name="version" value="${versionOf(r)}">
1550
- <label for="i">Instructions (needed to approve with changes or to send back)</label>
1551
- <textarea id="i" name="instructions" rows="4"></textarea>
1720
+ <label for="i">Instructions</label>
1721
+ <p class="muted hint" id="ih">Needed to send back. To approve with changes, write them or set the model below.</p>
1722
+ <textarea id="i" name="instructions" rows="4" aria-describedby="ih">${escapeHtml(o.kept?.instructions ?? "")}</textarea>
1723
+ ${blocked ? "" : modelBlock(r, deps, true, o.kept)}
1552
1724
  <div class="row">
1553
1725
  ${blocked
1554
1726
  ? ""
1555
- : `<button${r.kind === "run_request" || r.kind === "work_proposal" ? "" : ' class="primary"'} type="submit" name="decision" value="approve">Approve and run</button>
1556
- <button type="submit" name="decision" value="approve_with_changes">Approve with my changes</button>`}
1727
+ : `${floorUnmetHere ? "" : `<button${r.kind === "run_request" || r.kind === "work_proposal" ? "" : ' class="primary"'} type="submit" name="decision" value="approve">Approve and run</button>
1728
+ `}<button type="submit" name="decision" value="approve_with_changes">Approve with my changes</button>`}
1557
1729
  <button type="submit" name="decision" value="request_revision">Send back for revision</button>
1558
1730
  <button type="submit" name="decision" value="decline">Decline</button>
1559
1731
  </div></form>`