Skip to content

feat(bin): add opt-in typed dispatch resolution - #4692

Merged
kunchenguid merged 23 commits into
mainfrom
fm/typesafe-ai-firstmate-applicability-scout-r1
Sep 17, 2026
Merged

kunchenguid merged 23 commits into
mainfrom
fm/typesafe-ai-firstmate-applicability-scout-r1

Conversation

@kunchenguid

@kunchenguid kunchenguid commented Sep 17, 2026 •

Copy link
Copy Markdown
Owner

Intent

I just got access to typesafe.ai (docs start at https://docs.typesafe.ai/introduction). Study it and propose how I could apply it inside firstmate. One concrete idea to evaluate: crew dispatch routing might potentially be done by typesafe.ai instead of by the firstmate agent session deciding it. Anything we introduce in firstmate must be opt-in, gated on an env var TYPESAFE_API_KEY, because not every user has access - firstmate must keep working exactly as today when that key is absent. I have TYPESAFE_API_KEY stored in my Automic (av) vault; use it for live testing if you need to.

The deliverable is a proposal report, not a code change. If it turns out to be worth building, I will decide separately and this task can be promoted to ship.

ok i ONLY want resolve mode. so it should simply be the default behavior without the "--resolve" argument. and let's make sure to support the ".env" file in firstmate repo - if the api key is found there, we should activate this. oh but before starting implementation, can you figure out a way to benchmark baseline vs using jev for this dispatch step - how much time and money do we save?

alright time to get it implemented!

Resolve mode, as proposed in the scout report and approved above: a tool bin/fm-dispatch-resolve.sh that takes the written task brief, asks typesafe.ai's System One model (Jev) one Choice question over the natural-language dispatch rules already in config/crew-dispatch.json (which rule's "when" matches this brief, or none), and then in code applies a confidence floor, the matched rule's declared captain-approval gate and quota floor, each profile's declared provider and quota floor, and one quota-axi snapshot's spendPriority ranking to pick the concrete profile, printing the --harness/--model/--effort line for fm-spawn together with every candidate's evidence. Firstmate runs it in the same turn after writing the brief and uses today's routing whenever the result is ambiguous, escalated, an error, or the key is absent. The key comes from the environment or from a TYPESAFE_API_KEY line in the firstmate home's gitignored .env, is never printed or placed on a command line, and when absent the tool does nothing and firstmate dispatches exactly as today. The benchmark measured from real dispatches that today's routing costs a median of about $0.90 and 28.6 seconds per dispatch against about $0.24 and 2.75 seconds with the tool.

What Changed

  • Add a typesafe.ai Jev resolver that matches written briefs to dispatch rules, applies approval and quota gates, and emits a concrete spawn profile with candidate evidence.
  • Gate typed routing on TYPESAFE_API_KEY from the environment or the firstmate home’s .env, preserving existing routing for absent keys and all non-clear outcomes.
  • Extend dispatch configuration validation, shared provider/environment helpers, documentation, and shell test coverage for resolver behavior and safe fallback paths.

Risk Assessment

✅ Low: The opt-in resolver is well-bounded, preserves existing routing on non-clear outcomes, isolates the API key, and the reviewed quota-veto fixes maintain the documented invariants.

Verification record (worker-authored; complements the pipeline's Testing section)

The pipeline's test step could not run its own authenticated scenario because its attended vault prompt timed out; the captain approved the test step on the evidence below (docs/verification/dispatch-resolve.md holds the full record).

  • Automated suites pass. tests/fm-dispatch-resolve.test.sh and tests/fm-bootstrap.test.sh drive the executable interface with a fixture API and fixture quota: exhausted and unknown bounds, profile and rule floors, captain approval, low confidence, argument-boundary quoting, the absent, broken-symlink, and malformed rules-file cases, and child-environment probes proving TYPESAFE_API_KEY is absent from the curl and quota-axi child environments (the tool unsets the exported variable before any child starts, and the key reaches curl only as a header read from file descriptor 3).
  • Live scenarios 1-3 verified against the real endpoint (pipeline test step, final head): no key -> dispatch-resolve: off, exit 0, routing unchanged; key present with no rules file -> escalate / no rules to match, exit 0 (the round-20 fix); real endpoint with an invalid credential -> HTTP 401 becomes status: error, exit 0.
  • Authenticated live resolution (scenario 4) was demonstrated live earlier in this task at pipeline head 03c7fffb with the captain's approved vault prompt, the real endpoint, and the real key on 25 real briefs (fixture rules file, one fixture quota snapshot): 17 clear / 2 ambiguous / 6 escalate / 0 errors; rule match 20 of 25; hand-labeled profile 18 of 25; median API latency 220 ms. The one clear result that differed from the hand label is analyzed in the verification record (a synthetic tweak whose exemption text belongs in the captain's rule 4 when).
  • Between 03c7fffb and the final head the resolver's request, Choice question, response validation, and confidence handling are unchanged (verified by diff). The later fix commits changed candidate ordering in evaluate() (exhaustion and floor vetoes before uncertainty), output quoting, key hygiene, and the absent-rules-file fallback; all are fixture-covered and two of them were verified live above.
  • Unsafe-selection protections (quota exhaustion, profile and rule floors, ambiguity, approval gates, secret isolation) are fixture-verified because a real provider cannot be driven into exhaustion or a real answer forced below the confidence floor on demand.
  • Optional follow-up: a live re-run of the 25-brief fixture on main after merge, if desired.

Testing

Targeted resolver and bootstrap behavior tests passed, the real CLI preserved no-key and missing-rules fallback behavior, and the real endpoint produced a nonblocking structured 401 error. Authenticated Jev routing could not run because Automic’s attended approval was not granted. Unsafe-selection protections were exercised only with controlled fixtures, not against the live product.

  • Live validation: ⚠️ inconclusive - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Running dispatch resolution without TYPESAFE_API_KEY leaves existing routing in control ✅ pass live Live fallback and real-endpoint failure transcript: “no key preserves legacy routing” exits 0 with only the off diagnostic.
Enabling typed resolution without a rules file escalates to normal intake without blocking ✅ pass live Live fallback and real-endpoint failure transcript: “opted in but rules file absent” returns status escalate, reason “no rules to match,” and exit 0.
An API authentication failure becomes a structured nonblocking error ✅ pass live Live fallback and real-endpoint failure transcript: the real Typesafe endpoint returned HTTP 401, which the resolver reported as status error while exiting 0.
An authenticated Jev Choice selects the matching rule and emits a quota-ranked concrete profile with candidate evidence ⏸️ untested no The prior payload did not establish a live result because Automic Vault required attended human approval for TYPESAFE_API_KEY and timed out. Approve the av inject +TYPESAFE_API_KEY -- ... prompt and…
Quota exhaustion, profile floors, ambiguity, approval gates, and secret isolation resist unsafe selection ⏸️ untested no The prior payload established this behavior only through controlled API and quota fixtures, which do not qualify as live-product evidence. Drive these cases against the real running product with authe…
Evidence: Live fallback and real-endpoint failure transcript

Source: Live fallback and real-endpoint failure transcript

SCENARIO: no key preserves legacy routing
$ env -u TYPESAFE_API_KEY FM_HOME=<isolated-home> bin/fm-dispatch-resolve.sh <brief>
dispatch-resolve: off (TYPESAFE_API_KEY absent from the environment and ~/.no-mistakes/worktrees/016d88035d58/01M2PC6R7J66RVCNQWSHW91VPK/state/dispatch-live/.env)
exit=0

SCENARIO: opted in but rules file absent
$ TYPESAFE_API_KEY=<nonempty> FM_HOME=<empty-home> bin/fm-dispatch-resolve.sh <brief>
dispatch-resolve:
  status: escalate
  reason: no rules to match
exit=0

SCENARIO: real endpoint rejects invalid credential without blocking intake
$ TYPESAFE_API_KEY=<invalid-test-value> FM_HOME=<isolated-home> bin/fm-dispatch-resolve.sh <brief>
dispatch-resolve: error (http 401 after 138 ms: {"detail":{"error_type":"authentication_error","message":"Cannot authenticate with the server. Please check your API key and try again."}})
dispatch-resolve:
  status: error
  reason: http 401 after 138 ms: {"detail":{"error_type":"authentication_error","message":"Cannot authenticate with the server. Please check your API key and try again."}}
exit=0
Evidence: Automic attended-approval blocker

Source: Automic attended-approval blocker

automic vault: human approval required
- Outcome: ⚠️ 2 warnings across 1 run (6m19s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 7 issues found → auto-fixed (21) ✅
  • 🚨 bin/fm-dispatch-resolve.sh:248 - A clear result bypasses the repository's required catalog/authentication, reasoning-class, and completion-runway gates. evaluate considers only quota status, positive headroom, optional configured floors, and spendPriority. For example, a difficult rule containing a weaker high-priority model and a stronger lower-priority model selects the weaker model; likewise, a projected_exhaustion candidate with 900 seconds of runway can win a two-hour task. The quota-array-dispatch contract explicitly rejects both sequences. Remedy needs user authorization because adding catalog/auth/horizon machinery extends the stated inputs, while restricting these cases to escalation changes the intended savings and clear-result behavior.
  • 🚨 bin/fm-dispatch-resolve.sh:248 - Selecting exact(...) // wide(...) treats a model/product row as a replacement for its provider-wide row, although the dispatch contract defines named scopes as additional bounds. With all_models exhausted and model:foo healthy, this code uses only model:foo and can emit a clear profile for an exhausted account. Evaluate every applicable wide and exact row, vetoing on any exhausted/zero bound and using the effective limiting evidence for ranking.
  • ⚠️ bin/fm-dispatch-resolve.sh:235 - When a profile omits provider, the resolver substitutes a harness-to-primary-family map. A concrete {harness:&#34;opencode&#34;, model:&#34;anthropic/...&#34;} profile is therefore ranked against Codex quota and may produce a clear route from unrelated evidence. This conflicts with the existing rule that authoritative multi-provider routing establish the family from the harness catalog rather than infer it. Decide whether typed resolution should require explicit providers for multi-provider harnesses or add catalog discovery; that schema/behavior choice needs user approval.
  • ⚠️ bin/fm-dispatch-resolve.sh:139 - The resolver's private schema validation only requires a nonempty harness string and does not enforce the verified harness or effort rules that bootstrap applies. If a human-edited rule uses {harness:&#34;spaceship&#34;, provider:&#34;codex&#34;}, Jev can match it and this tool can print a clear --harness spaceship result; fm-spawn then refuses instead of the resolver returning the required actionable configuration error/fallback. Reuse equivalent harness and effort validation at the resolver boundary.
  • ⚠️ bin/fm-dispatch-resolve.sh:262 - A malformed API choice of rule_0 is converted to index -1, which jq interprets as the final rule, so the resolver can silently route using the last rule rather than return an error. Validate that the numeric suffix is within 1..rules.length before indexing.
  • ⚠️ bin/fm-dispatch-resolve.sh:124 - The shell globs accept values outside the documented 0–1 range: 1.01 matches 1.0*, and 0.6junk matches 0.[0-9]*. The former makes every normal response ambiguous; the latter performs the paid API and quota calls before jq fails resolution. Parse the value numerically and enforce 0 &lt;= floor &lt;= 1 before the network call.
  • ⚠️ bin/fm-dispatch-resolve.sh:186 - The new default_when schema branch adds a second configurable matching criterion for the already-required “or none” choice, together with fallback and validation paths. The stated intent requires only choosing a matching rule or none and does not require users to redefine what none means. Consider removing default_when and exposing one fixed none option; retaining this additional behavior requires user approval.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:290 - The resolver checks only that selection.spendPriority is non-null, while the shared snapshot validator does not validate this field. A documented --quota snapshot containing a string or object spendPriority therefore passes validation and reaches min_by/max_by; jq orders mixed JSON types and can emit a clear but incorrect profile. Require a numeric spendPriority at the resolver boundary, otherwise mark the row unrankable or reject the snapshot.
  • ⚠️ bin/fm-dispatch-resolve.sh:287 - The change accepts an undocumented second provider inside profile.floor and uses it instead of the profile's declared provider. No intent requirement needs this override: for example, a Codex profile with floor.provider: &#34;claude&#34; is admitted or rejected using Claude quota even though the documented profile floor belongs to that candidate. Remove provider support from profile floors and always evaluate their scope against the profile provider.

🔧 Fix applied.
3 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:232 - Response validation accepts any numeric confidence rather than the documented 0–1 probability range. A malformed response with confidence: 2 and a valid choice therefore produces a clear profile instead of the promised malformed-response error. Validate 0 &lt;= confidence &lt;= 1 before resolving.
  • ⚠️ bin/fm-dispatch-resolve.sh:290 - When a profile floor fails, the reported top-level scope, percentage, and runway come from the lowest-percent applicable row rather than the floor's named scope. For example, an all_models floor failing at 79% beside a model:sonnet row at 10% reports scope=model:sonnet remaining=10% while claiming the all_models floor failed. Select and report the actual matching floor row, while retaining all bounds separately.
  • ⚠️ bin/fm-dispatch-resolve.sh:91 - The new --status execution mode exceeds the authoritative request for “ONLY ... resolve mode.” The resolver already no-ops safely when the key is absent, so firstmate can invoke the normal resolve path after writing the brief without a separate preflight mode. Remove --status and its duplicated AGENTS/docs path unless the author explicitly wants this additional mode.

🔧 Fix applied.
2 issues (1 error, 1 warning) still open:

  • 🚨 bin/fm-dispatch-resolve.sh:80 - The required “or none” option is not generic: it excludes simple root-cause bug fixes even when the configured rules contain no bug-fix rule. For example, with only a fresh-news rule, a simple root-cause bug matches neither option as written, encouraging Jev to select an unrelated rule and potentially produce a clear wrong profile. The appended task taxonomy is also an unnecessary second definition of matching policy; narrow this to a fixed statement that no listed rule applies.
  • ⚠️ bin/fm-dispatch-resolve.sh:149 - The canonical crew-dispatch schema and bootstrap accept a default-only configuration or rules: [], but the resolver labels it malformed and exits 2. Once the API key is enabled, such an existing valid configuration can no longer return to normal routing. Decide whether default-only files should resolve the default directly or produce a normal non-clear fallback instead of a configuration error.

🔧 Fix applied.
1 error still open:

  • 🚨 bin/fm-bootstrap.sh:1175 - This contradicts the required guarantee that “firstmate must keep working exactly as today when that key is absent.” Bootstrap now rejects every existing Pi, Pi-signed, OMP, or OpenCode profile lacking provider, even without TYPESAFE_API_KEY. Such profiles were previously valid—including the prior shipped example—and repository instructions treat the resulting malformed configuration as blocking dispatch. Preserve the old schema when the feature is off; enforce the provider requirement only at the opted-in resolver boundary, unless this breaking migration is explicitly approved.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:227 - Response validation ignores usage, although text rendering indexes .tokens.input_tokens. A response with a valid choice/confidence but &#34;usage&#34;:&#34;bad&#34; passes validation, then jq rendering fails; the unconditional final exit 0 leaves no structured error outcome. Validate the optional usage shape or render it defensively and convert rendering failures into status: error.
  • ⚠️ bin/fm-dispatch-resolve.sh:332 - Duplicate concrete profiles are accepted and counted as separate equal-priority candidates. A rule containing the same profile twice therefore returns escalate: genuine spendPriority tie, even though repository dispatch policy says duplicate profiles are configuration errors. Reject duplicate concrete profiles at the opted-in resolver validation boundary before requesting or ranking.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:322 - A rule floor with unavailable evidence is treated as a confirmed below-floor result. For example, if the named scope is absent or has status: unknown, floor_ok returns false and the matched rule silently falls through to the default, which can produce a clear profile. Distinguish a known percentage below the floor from missing/unknown evidence; the latter should produce a non-clear outcome rather than authorize default routing.
  • ⚠️ bin/fm-dispatch-resolve.sh:235 - Response validation checks only that probabilities is an object. A response such as &#34;probabilities&#34;: {} or one containing string/out-of-range values is accepted and can yield clear, or an ambiguous result whose advertised fallback evidence is unusable. Validate that every offered choice has a numeric probability in 0–1 and reject malformed probability evidence as a structured error.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:235 - The response accepts values that cannot be probabilities because it checks only individual bounds, not that the distribution totals approximately 1. For example, the test fixture's all-zero map passes and can produce a clear route despite supplying no probability mass. Reject distributions whose sum is not approximately 1 before resolving a profile.
  • ⚠️ bin/fm-dispatch-resolve.sh:306 - floor_state distinguishes unknown from below, but the profile path merges both states and reports an absent or unknown floor row as a confirmed shortfall. A profile whose named scope is missing therefore emits profile floor ... below ...% with null evidence and may be excluded while another candidate clears. Preserve the distinction and report unverifiable evidence rather than a false below-floor result.

🔧 Fix applied.
4 issues (1 error, 3 warnings) still open:

  • 🚨 bin/fm-dispatch-resolve.sh:208 - With TYPESAFE_API_KEY present and at least one rule, a missing curl exits 2 instead of producing status: error. The authoritative intent requires firstmate to use today's routing whenever resolution is an error, while AGENTS.md only defines fallback for structured error/off outcomes. Return the normal structured error outcome here so this reachable dependency failure preserves existing routing.
  • ⚠️ bin/fm-dispatch-resolve.sh:97 - The new --json output mode is not required by the approved intent, which specifies the fm-spawn profile line and candidate evidence output. It adds a second public serialization contract; remove this option unless the additional interface is explicitly desired.
  • ⚠️ bin/fm-dispatch-resolve.sh:95 - The new --rules option adds a parallel rules source beyond the required firstmate-home config/crew-dispatch.json path. No stated requirement needs arbitrary rule files; remove this option and retain the canonical configuration source unless this extension is explicitly approved.
  • ⚠️ bin/fm-dispatch-resolve.sh:96 - The new --quota option permits externally supplied quota evidence instead of the required single quota-axi snapshot. This alternate acceptance path is not required by the stated runtime intent; remove it from the public tool and keep fixture injection inside the test harness unless explicitly approved.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:259 - measured accepts only provider-level status known, although the validated quota schema also permits partial. A valid partial provider with a known applicable all_models row is therefore rejected before that row is evaluated, causing an unnecessary escalation instead of the required spendPriority ranking. Evaluate applicable row statuses rather than rejecting the whole provider-level partial state.
  • ⚠️ bin/fm-dispatch-resolve.sh:69 - The four new environment overrides for confidence floor, model, base URL, and timeout add public operating modes not required by the approved intent; notably the endpoint and model overrides can stop the tool from using typesafe.ai's Jev as specified. Remove these overrides and retain fixed implementation constants unless this tuning surface is explicitly desired.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:127 - The resolver requires an explicit provider only for four multi-provider harnesses, but the shared provider map has no entry for valid agy or rovo profiles. For example, a default-only { &#34;harness&#34;: &#34;agy&#34; } profile passes validation, then provider_of returns null and the sole candidate escalates as unrankable. Decide whether these harnesses need authoritative mappings or must declare provider, and align validation and the documented optional-provider contract accordingly.

🔧 Fix applied.
1 warning still open:

  • ⚠️ docs/configuration.md:451 - The resolver now requires an explicit provider for every Pi profile, but the linked starting configuration at docs/examples/crew-dispatch.json:24 still has a provider-less Pi default. Copying that documented example and enabling TYPESAFE_API_KEY therefore exits 2 with a configuration error before resolution. Add the Pi profile's established provider to the example so the advertised starting configuration works with this feature.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:109 - The resolver's verified-harness list omits the repository-supported gemini adapter. A profile such as {&#34;harness&#34;:&#34;gemini&#34;,&#34;provider&#34;:&#34;google&#34;} is rejected as malformed before resolution, despite the explicit-provider rule being intended to cover unmapped Gemini profiles. Add gemini here and align bootstrap's equivalent validator.
  • ⚠️ bin/fm-dispatch-resolve.sh:135 - Provider declarations are checked only for being non-empty, while quota snapshots require provider IDs matching ^[a-z0-9]+(-[a-z0-9]+)*$. Thus a typo such as provider: &#34; claude&#34; passes configuration validation, triggers the external request, and later escalates as a missing provider instead of producing the promised actionable configuration error. Apply the quota provider-ID invariant to profile and rule-floor providers in both resolver and bootstrap validation.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-quota-axi-lib.sh:13 - The provider-ID regex uses $, which can match before a final newline. A JSON provider such as &#34;claude\n&#34; therefore passes both bootstrap and resolver validation; with a nonempty rules array the resolver sends the brief to typesafe.ai before later treating that provider as absent from the quota snapshot, contrary to the promised configuration error before any request. Use a strict end-of-string anchor such as \z in the shared regex.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:149 - Runtime validation omits the existing select schema checks enforced by bootstrap. If an inherited or human-edited config changes mid-session to select: &#34;mystery&#34;, the resolver sends the brief externally and silently applies quota-balanced selection instead of returning the required actionable configuration error. Validate that present select is a non-empty string equal to quota-balanced before any request.
  • ⚠️ bin/fm-dispatch-resolve.sh:340 - Low-confidence and approval-gated outcomes bypass evaluate, with approval explicitly returning candidates: []. For example, a 0.41 response selecting a two-profile rule prints no candidate lines despite already taking the quota snapshot. This contradicts the required and documented promise to print every candidate's evidence, including before escalation. Evaluate and render the applicable profiles for evidence without emitting a chosen profile on non-clear outcomes.

🔧 Fix applied.
3 issues (1 error, 2 warnings) still open:

  • 🚨 bin/fm-bootstrap.sh:1147 - The intent requires everything introduced here to be opt-in and says that without TYPESAFE_API_KEY Firstmate must work exactly as today. Bootstrap nevertheless validates the new provider, floor, and approval fields unconditionally. For example, a previously accepted profile containing &#34;provider&#34;:&#34;Anthropic&#34; now emits an actionable CREW_DISPATCH diagnostic even when the key is absent. Gate resolver-only validation on the same environment/.env activation condition, or ask whether changing non-opted-in bootstrap behavior is intended.
  • ⚠️ bin/fm-dispatch-resolve.sh:213 - The mutable rules file is reread for request construction, response validation, and final resolution. If its rule text/profile changes during the API call while the rule count remains the same, Jev can answer rule_1 for the old condition and the resolver can silently dispatch the new rule_1 profile. Snapshot the file once before validation and use that immutable copy for every subsequent read.
  • ⚠️ bin/fm-dispatch-resolve.sh:369 - Configuration and quota strings are interpolated directly into the line-oriented output. A valid multiline when or model value can inject additional lines—including a second apparent profile: line—so the Firstmate instruction to pass the profile line becomes ambiguous. Escape or flatten control characters in all dynamic fields during rendering while preserving the actual chosen profile data.

🔧 Fix applied.
5 issues (3 errors, 2 warnings) still open:

  • 🚨 bin/fm-quota-axi-lib.sh:103 - This adds an agy -&gt; agy mapping to the shared provider table used by the pre-existing fm-quota-choose.sh. Consequently, with no TYPESAFE_API_KEY, an Agy candidate that previously failed as an unknown harness can now be selected. This contradicts the required constraint that everything introduced be opt-in and that Firstmate work exactly as before when the key is absent. Keep the new mapping resolver-local or ask the user to authorize changing the existing helper.
  • 🚨 bin/fm-bootstrap.sh:1123 - Bootstrap now derives its baseline verified-harness set from fm_control_harnesses, which includes gemini; before this change its dispatch validator rejected Gemini. A providerless Gemini profile is therefore accepted even when typed resolution is inactive, changing no-key behavior contrary to the explicit opt-in requirement. Preserve the former baseline set when typed_active is false, or obtain approval for this unrelated behavior change.
  • 🚨 bin/fm-dispatch-resolve.sh:389 - Dynamic profile values are flattened but not shell-escaped. A valid configuration with model foo --harness grok emits --harness claude --model foo --harness grok; passing the promised profile line to fm-spawn silently overwrites the selected harness. Shell metacharacters can also alter the command. Render every emitted value as one safely quoted shell argument rather than merely replacing control characters.
  • ⚠️ bin/fm-dispatch-resolve.sh:300 - Candidates with no applicable quota row or an applicable row whose status is unknown still receive neither eligible nor unranked. For example, a partial provider with known account evidence and an unknown exact-model row prints not eligible and is omitted from the clear-result unranked note. This contradicts the repository invariant that missing or unmeasurable quota remains disclosed uncertainty while the candidate stays eligible. Mark these paths eligible-unranked so the note and evidence accurately preserve that uncertainty.
  • ⚠️ bin/fm-dispatch-resolve.sh:211 - The change introduces a separate default-only mode that skips Jev and can emit a clear profile when rules is absent or empty. The stated intent requires one Choice over the natural-language rules and does not require the resolver to replace existing default routing when there are no rule options. Remove this extra branch and return such configurations to the existing intake unless the user explicitly wants direct default-only resolution.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:296 - Unverifiable profile floors and unknown applicable rows are classified as eligible-unranked before checking concrete exhaustion. For example, a candidate with a known exhausted all_models row plus an unknown exact-model row is reported eligible-unranked rather than ineligible, contradicting the documented rule that any exhausted applicable bound vetoes the candidate. Apply the exhausted_now and known-zero checks before uncertainty branches while retaining all evidence.

🔧 Fix applied.
3 issues (1 error, 2 warnings) still open:

  • 🚨 bin/fm-dispatch-resolve.sh:94 - When TYPESAFE_API_KEY arrives through the environment, Bash preserves its exported attribute, so every subsequently launched jq, curl, and quota-axi process inherits the secret. The key therefore crosses into quota-axi even though it only needs to reach curl through fd 3. Copy it into a non-exported private variable and unset TYPESAFE_API_KEY before launching child processes.
  • ⚠️ bin/fm-bootstrap.sh:1186 - The required absent-key behavior is “exactly as today,” but malformed legacy model/effort configurations now report an expanded provider-related diagnostic even when typed resolution is inactive. For example, a numeric profile model previously produced use profile model and effort must be non-empty strings when present; it now appends the inert provider constraint. Preserve the original diagnostic on the no-key branch and use the expanded message only when $typed is true.
  • ⚠️ docs/verification/dispatch-resolve.md:18 - The change originally recorded the intent's benchmark—83 dispatches, median $0.90/28.6s today versus about $0.24/2.75s with the tool—but a fixer commit removed that entire verification section. The authoritative intent still states these measured figures; restore the benchmark table and its measurement context unless the user approves dropping this evidence.

🔧 Fix applied.
1 warning still open:

  • ⚠️ bin/fm-dispatch-resolve.sh:107 - With TYPESAFE_API_KEY set but the optional config/crew-dispatch.json absent, every instructed intake exits 2 at the readability check. AGENTS.md only routes ambiguous, escalate, error, or off back through today's intake, while configuration errors are explicitly not selected around, so merely enabling the key can block dispatch instead of falling back as required. Confirm whether an absent optional rules file should behave like zero rules (escalate: no rules to match); if so, reserve exit 2 for an existing but unreadable/malformed file.

🔧 Fix applied.
4 issues (2 errors, 2 warnings) still open:

  • 🚨 bin/fm-dispatch-resolve.sh:299 - The claimed exhaustion fix remains bypassable: an accepted quota snapshot may have quotaSemantics.status: &#34;unknown&#34; with an applicable unknown row whose runway.status is exhausted_now, but evaluate returns eligible-unranked before inspecting rows. This contradicts the documented invariant that any exhausted applicable bound makes the candidate ineligible. Check applicable exhausted_now evidence before provider-status uncertainty.
  • ⚠️ bin/fm-dispatch-resolve.sh:314 - A known failed profile floor is ignored when another applicable row is unknown. For example, floor: {scope:&#34;all_models&#34;,min_percent:50} with a known 10% all-models row and an unknown exact-model row becomes eligible-unranked at line 314 instead of ineligible for the declared floor. Handle profile_floor_state == &#34;below&#34; before unrelated unknown-row uncertainty.
  • 🚨 bin/fm-bootstrap.sh:1120 - When bootstrap is launched with an exported TYPESAFE_API_KEY, the newly added typed validation reads it but leaves the original exported variable intact, so jq and every other bootstrap child inherit the credential. Copy it into a non-exported private variable and unset TYPESAFE_API_KEY before bootstrap launches child processes, then use the private value for activation detection.
  • ⚠️ bin/fm-dispatch-resolve.sh:113 - The absent-file fallback uses -e, which is false for a broken symlink. Thus an existing but unreadable config/crew-dispatch.json symlink silently returns no rules to match instead of the required actionable exit 2. Distinguish a genuinely absent directory entry from an existing symlink, such as by also checking -L.

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Test** - 2 warnings
  • ⚠️ Authenticated Jev resolution could not be demonstrated because Automic Vault required attended human approval and the prompt was not approved before timeout. Approve av inject +TYPESAFE_API_KEY -- ... and rerun the live resolver scenario to verify real rule matching and profile selection.
  • ⚠️ live validation verdict: inconclusive (3 of 5 scenarios were driven live against the product); untested: An authenticated Jev Choice selects the matching rule and emits a quota-ranked concrete profile with candidate evidence, Quota exhaustion, profile floors, ambiguity, approval gates, and secret isolation resist unsafe selection
  • Live validation: ⚠️ inconclusive - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Running dispatch resolution without TYPESAFE_API_KEY leaves existing routing in control ✅ pass live Live fallback and real-endpoint failure transcript: “no key preserves legacy routing” exits 0 with only the off diagnostic.
Enabling typed resolution without a rules file escalates to normal intake without blocking ✅ pass live Live fallback and real-endpoint failure transcript: “opted in but rules file absent” returns status escalate, reason “no rules to match,” and exit 0.
An API authentication failure becomes a structured nonblocking error ✅ pass live Live fallback and real-endpoint failure transcript: the real Typesafe endpoint returned HTTP 401, which the resolver reported as status error while exiting 0.
An authenticated Jev Choice selects the matching rule and emits a quota-ranked concrete profile with candidate evidence ⏸️ untested no The prior payload did not establish a live result because Automic Vault required attended human approval for TYPESAFE_API_KEY and timed out. Approve the av inject +TYPESAFE_API_KEY -- ... prompt and…
Quota exhaustion, profile floors, ambiguity, approval gates, and secret isolation resist unsafe selection ⏸️ untested no The prior payload established this behavior only through controlled API and quota fixtures, which do not qualify as live-product evidence. Drive these cases against the real running product with authe…
  • bash tests/fm-dispatch-resolve.test.sh
  • bash tests/fm-bootstrap.test.sh
  • quota-axi --json | jq '{schemaVersion, providers: [...]}'
  • Live no-key invocation using env -u TYPESAFE_API_KEY ... bin/fm-dispatch-resolve.sh
  • Live missing-rules invocation with a nonempty activation sentinel
  • Live request to the real Typesafe endpoint with an intentionally invalid credential
  • Attempted authenticated invocation with av inject +TYPESAFE_API_KEY -- ...
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Add bin/fm-dispatch-resolve.sh, which resolves one concrete crewmate or
scout profile from a written brief with typesafe.ai's System One model:
one Choice question over the rules' `when` texts, then the confidence
floor, the rule's `approval` and `floor`, each profile's `provider` and
`floor`, one quota-axi snapshot, and the spendPriority argmax all in code.
It is off unless TYPESAFE_API_KEY is in the environment or the home's
gitignored .env; off means one stderr line, exit 0, and no network call,
so firstmate dispatches exactly as before. The key reaches curl on a file
descriptor, never argv.

Extract fmx_env_get into bin/fm-env-lib.sh as the one .env accessor and
the harness-to-provider table into bin/fm-quota-axi-lib.sh so the new
tool and bin/fm-quota-choose.sh share one owner each. Bootstrap validates
the four new optional dispatch fields. Document the schema, the operator
contract, the AGENTS.md intake step, and the live and benchmark evidence.
@kunchenguid
kunchenguid merged commit 69d660a into main Sep 17, 2026
15 checks passed
@kunchenguid
kunchenguid deleted the fm/typesafe-ai-firstmate-applicability-scout-r1 branch September 17, 2026 05:32
jorguez96 added a commit to jorguez96/firstmate that reference