/mcp-qsql-suggester:qsql-coderfrom mcp-qsql-suggester
Draft one finance qSQL statement via the fine-tuned qwen specialist (kxqsql MCP) — parse + KX qlint C9 + multi-seed execution against a dummy table, then Bash-verified against an independently derived reference. Use whenever the task is to write or fix a single kdb+/q table query over market or trading data (trade, quote, order-book, execution tables; VWAP, TWAP, PnL, spread, returns) AND either the request carries as-of or time-window semantics ("as of", "prevailing quote", "the quote in effect at each trade", "per 5 minutes", "1-minute bars", "OHLC", "rolling 20-day", "moving average", "cumulative") or the request supplies a formula, a q snippet, or a worked example to check against. For finance qSQL with none of those — one table, one filter or one aggregate — use qsql-coder-quick instead. Do NOT use for non-finance data, for generic q (IPC, .z handlers, file I/O, system commands, admin scripts), or for multi-step workflows.
Ships in mcp-qsql-suggester. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Delegate a single qSQL generation task to the kxqsql MCP tool
(qwen fine-tune served by local vLLM). The MCP draws several independent
candidates per call at a non-zero temperature in growing rounds (e.g.
4 -> 8 -> 16), gates each on raw q parse + KX qlint C9, executes valid
candidates against a dummy table (built from the supplied table_schemas)
across multiple seeds, and clusters candidates by cross-seed execution-
equivalence — returning the shortest-code candidate from the largest
(winning) cluster. Present the drafted q code, the verdict, and an
optional one-sentence idiom note.
kxqsql MCP tool must existIf mcp__kxqsql__generate_qsql is not among your available tools, the server
is not registered for this project. Stop and report — do not work around
it. Three specific non-workarounds, because each is tempting: do not attempt
the call anyway (a call to a tool that does not exist yields a harness error
that says nothing about the cause), do not substitute q you wrote yourself (a
silent substitution hides which model answered, and this skill's whole output
contract is about the specialist's draft), and do not run the formatter (no
case describes this situation — the "do not hand-render" rule governs
formatter output, not a pre-flight abort). Reply in plain text:
The
kxqsqlMCP server is not registered in this project, so I cannot reach the qSQL specialist. Add it to a project-scope.mcp.json— see themcp-qsql-suggesterREADME § "Point your client at your server" — and then restart Claude Code: MCP config is read once at startup, so editing.mcp.jsonmid-session has no effect.
Then stop. This is the one path that produces no formatter output at all.
qsql-coder and qsql-coder-quick call the same MCP tool with the same
arguments, so running both samples the model twice for one question. If
qsql-coder-quick has already run on this instruction in this conversation,
do not run: its draft stands. If you now think the task warranted full
mode's Bash-verify after all, say that in one line and let the user ask for
it — do not re-run on your own.
| Param | Type | Required | Default | Notes |
|---|---|---|---|---|
instruction | string | yes | — | Single-task qSQL description. Not a multi-step workflow; not non-q work (IPC, file I/O, system commands). |
table_schemas | dict of name→q schema string | yes | — | e.g. {"trade":"\time`sym`price`size!`p`s`f`j"}`. The MCP tool refuses calls without it — qwen was trained with schemas in context. |
max_rounds | integer | no | the server's configured round count (e.g. 3 for 4→8→16) | Ceiling on self-consistency rounds this call may use. Requesting fewer is always honored; requesting more is clamped to the server's MCP_QSQL_SC_ROUND_CAPS. |
If instruction is missing or vague, ask the user.
Step 0 — look for the real schema before drafting one. An invented schema
is the quiet failure mode. The column names will match (you wrote both), so
the candidates run and agree — but on a dummy table whose types and value
ranges need not resemble the user's data, which is exactly the input a
semantic defect hides in. A wrong name fails loudly (passed=false); a
wrong type or distribution fails silently. So spend one search first:
Anything the user already pasted in this conversation — meta output, a
([] ...) table definition, a DDL snippet — is authoritative. Use it and
skip the rest.
Otherwise search the project for a definition of each table the instruction names:
grep -rnE '^[[:space:]]*(trade|quote)[[:space:]]*:[[:space:]]*\(\[' \
--include='*.q' --include='*.k' . | head -20
Substitute the actual table names. Also worth a look: any schema or loader
.q file, and meta / cols output checked into the repo.
Only if that finds nothing, fall through to the options below.
Whichever route produced the schema — found or drafted — it still reaches the
user in the Schemas used block, so a wrong guess is visible in the output
rather than buried in the call.
The MCP tool rejects calls without table_schemas, so you cannot
silently call it with an empty schema. Do NOT silently infer a schema
either — instruction text often names columns but rarely specifies q
types unambiguously. Instead:
"You haven't provided a table schema. Want me to draft one based on your instruction (and confirm with you before calling qwen), or would you rather provide the schema yourself in q notation (e.g.
{name: "\col1`col2!`type1`type2"}`)?"
join,
lj, aj, wj, "lookup against", "enrich with", "match against",
"cross-reference"). Write one schema entry per table, then present
the full dict for confirmation. Single-table example:
"I'll use:
{"trade":"`time`sym`price`size!`p`s`f`j"}. Confirm or correct." Multi-table example (join): "I'll use:{"trade":"`time`sym`tradeId`price`size!`p`s`j`f`j", "quote":"`time`sym`bid`ask!`p`s`f`f"}. Confirm or correct each entry." Only call the MCP after the user confirms (or supplies corrected versions).
Common q type chars: p (timestamp ns), t (time ms), d (date),
s (sym), f (float64), j (long), i (int), b (bool), c (char),
g (guid), n (timespan), h (short), e (real), m (month),
u (minute), v (second), z (datetime), x (byte).
Call the MCP tool mcp__kxqsql__generate_qsql with the gathered
parameters plus include_candidates=false — every field this skill reads
below (q_code, passed, lint_gate, final_issues, rounds_used,
candidates_generated, winning_cluster_size, winning_cluster_fraction,
tie_occurred, winning_result_vacuous) is at the top level of the return; the per-candidate
candidates list is debugging/audit detail this skill never reads, so
omitting it saves tokens on this side. Then branch on the structured
return.
The MCP's passed=true means the q_code ran without raising — it
does NOT mean the q_code computes the user's intended answer. A common
class of failure (e.g. wavg applied AND then divided by sum size
again, double-applying weighted average) parses cleanly, lints cleanly,
and executes without error — yet returns the wrong value. Semantic
intent has to be checked separately by Bash-verify against a reference
(see "Bash-verify protocol" below).
passed=true — decide whether to Bash-verify| Signal in the q_code or return | Action |
|---|---|
Uses a high-risk named idiom: wavg, wsum, mavg, msum, mmax/mmin/mcount/mdev/mmedian, fby, xexp, prds, sums/sum mixed with wavg-family | Bash-verify (these idioms condense multiple ops into one call; easy for qwen to over-apply or combine with redundant arithmetic) |
Functional form ![...] or ?[...] with nested parse-tree aggregates | Bash-verify (parse-tree composition is fragile) |
winning_result_vacuous=true — the returned draft's result was empty (or all-null) on every dummy dataset the server tried | Bash-verify — whatever the cluster numbers say, nothing about this draft was tested against data: its agreement is agreement on code text alone. The verify data is built from the constants in both the draft and your reference, so it often reaches rows the server's did not |
winning_cluster_fraction < 0.6 (weak majority — the winning cluster carries under 60% of the candidates generated) or tie_occurred=true | Bash-verify — qwen was split across answers, so verify against an independent reference. 0.6 rather than 1.0: a lone dissenter out of 8 is normal sampling noise at temperature 0.8, not a signal, and verifying every one of those spends a q process on nothing |
| User provided a q snippet / canonical form / formula in the prompt | Bash-verify — even when no other trigger fires. The priority-1 reference is free (no need to draft), and catching divergence is high-value. A reference you don't use is a reference wasted. |
| None of the above | Trust the gate. No verification needed. Present q_code + verdict directly. |
tie_occurred=true is redundant while that threshold stays above 0.5, and
deliberately kept. A tie means two or more clusters share the top weight, and
clusters are disjoint, so the winner holds at most half the total weight —
winning_cluster_fraction is winning_cluster_size / candidates_generated
(mcp_server/loop.py), whose denominator also counts candidates excluded from
clustering, so the real fraction is at most 0.5 and usually lower. Any
threshold above 0.5 therefore fires on every tie by itself. It is kept
because it costs nothing, states the intent independently of the number, and
becomes load-bearing again the moment somebody tunes the threshold to 0.5 or
below.
Once a row has fired, confirm q is reachable before acting on it.
Nothing in the table above can tell you whether this project has a working q —
the MCP runs its own embedded q on the server side, which says nothing about
your side. Check lazily, only after a trigger fires, so the common case-A
path costs no extra Bash call:
echo '-1 "q ok"; exit 0;' | timeout -k 5 10 q -q 2>&1 | head -2
q is reachable only if that prints q ok. Do not use q --version: q has
no such flag, so it opens a REPL and waits for input — it hangs whenever stdin
is open, and when it does return it prints nothing, so it proves neither that
q runs nor that the licence is good. (The echo ... | q form is safe here
because the snippet has no backticks; the rule below against piping applies to
q code with symbols in it.)
If that fails — no q on PATH, no licence, anything other than q ok —
Bash-verify is not available and this becomes an honest case A rather than a silent one. Render
case A with "verification_unavailable": "no_q". Do not just fall through
to the "None of the above" row: that prints a reason list beginning "no
high-risk idiom", which is false about code that has one. With the field set
the verdict reads "Not verified — q is not on PATH, so Bash-verify could
not run" instead.
Without q this skill's output is qsql-coder-quick's output plus an accurate
label. That is a degradation, not an error: mention /qsql-coder-quick only
if the user asks why nothing was verified.
passed=false — Opus rewrites, then Bash-verifiesNo self-consistency cluster survived gating — every candidate across every
round either failed parse/lint/exec or produced a degenerate result;
final_issues explains why the first-generated candidate specifically
failed. Do not ship qwen's broken draft as the answer.
Write your own independent q version from the instruction + schema. If the instruction contains an explicit formula, literal- translate it (priority 2 in the reference priority system); otherwise use your own qSQL knowledge. Do not patch qwen's draft — the value of this step is that it is an independent reference, and a fix derived from the draft inherits the draft's framing.
One exception to that independence, and only one: if final_issues names a
qlint rule (e.g. GLOBAL_PEACH, INVALID_ESCAPE), that is a q-level
constraint rather than a mistake specific to qwen — avoid the same
construct in your own version. Reading a rule name is not the same as
patching the draft.
Bash-verify your version against a dummy table matching the
schema. Check it executes without error and the output shape looks
reasonable (correct columns, correct row count given the grouping).
If q is not reachable (the same check as above), steps 1 and 2 are not
available to you: you could write a version but not verify it, and this skill
does not present unverified q as an answer. Render case D with
opus_could_write=false and "verification_unavailable": "no_q". The
second field is what keeps the verdict honest — without it case D reports
"task is outside my q knowledge or the instruction is genuinely ambiguous",
when in fact the instruction may have been perfectly clear and only the
verification step was missing.
Present per outcome:
final_issues shown as
a secondary "what qwen tried" note.When writing q yourself (rewrite path on passed=false, or drafting
the reference via priority 2/3), you may probe q via
echo '<expr>' | q -q to confirm an idiom before committing.
You ALREADY know (do NOT probe): standard select / update /
exec / delete with where / by, sorts (asc / desc / xasc /
xdesc), type casts (`long$, `float$, `symbol$,
`timestamp$), common aggs (count / distinct / sum / avg /
first / last / min / max / prev / next), enlist / raze /
ungroup, basic lj / 3-arg aj[`sym`time; t; q].
You MAY probe these (established failure classes):
?[t;w;b;c] / ![t;w;b;c]: b and c are dicts,
not lists. (enlist `name)!enlist (op;...), not
enlist (op;`a;`b). The parse-tree expression (op;a;b) is data,
not a function call.n xbar v arg order + type-pairing: 0D01 for p (ns),
00:01:00 for t (ms), integer minutes for u. Literal 60 on a
p column buckets by 60 nanoseconds.wavg / wsum arg order: weight wavg value. wavg[size;price]
already computes sum[price*size] % sum size — do not divide
again.fby shape: (agg; col) fby key — different from by.':, \:, /:,
differ, each-prior.xbar: 0D... (timespan) vs
t-type (ms) compares/casts; p arithmetic with n.Budget: 2–3 probes per invocation. More → escalate to the user; the instruction or schema is probably ambiguous. Probing confirms idiom correctness, not result correctness — post-write Bash-verify against the reference is still required.
The protocol compares runtime results, not code text. The q expression we compare qwen's draft against is the reference. Pick one by priority order (confidence decreases 1 → 3):
User-provided q code in the prompt — anything labelled "reference", "canonical", "expected", "conventional", "equivalent to ...", or shown as a worked-example q snippet. Use verbatim; confidence: high.
Strict reading of "user-provided": the q code must appear in
the user's original message — not in the instruction
ARGUMENT you (Opus) pass to this skill. If you translated the
user's natural-language phrase ("price-weighted volume") into q
(price wavg volume) as part of your pre-call cleanup and
embedded it in the skill ARGUMENTS or in a "Reference idiom:"
label inside your own invocation, that is priority 3 (your
own translation), not priority 1. Self-injected q code is yours,
regardless of how you labelled it on the way in.
A formula explicit in the instruction (e.g. "VWAP =
sum(pricesize)/sum(size)"*). Literal-translate the formula to
q — do NOT rewrite into a more idiomatic form (e.g. do NOT collapse
it back into wavg); literal translation breaks the "both share the
same misapplication" failure mode. Confidence: high.
Your own independent translation of the instruction in q. Confidence: medium — qwen and you may share idiomatic assumptions; hedge in the verdict ("verified against my own translation, which may share assumptions with qwen's output").
Throughout this skill, bare reference means "whichever priority is in play" (generic); qualifiers like user-provided / priority-1 / priority-3 narrow to a specific one.
Compare results (not code) against the same dummy data. Write the q
to files in a fresh mktemp -d directory and run
timeout -k 5 60 q verify.q -q </dev/null from inside it — do NOT pipe via
echo '...' | q -q or q -q <<EOF heredoc. Reason: q code is full of
backtick-prefixed symbols (`sym, `time, etc.); on many
shells the backticks inside echo / heredoc trigger command
substitution and get stripped before reaching q, producing
'( error or silently malformed code. The temp-file approach sidesteps shell quoting entirely. The trailing **</dev/null** is load-bearing: after running the file, q tries to enter the REPL and read from stdin; without </dev/null(and without a trailingexit 0;in the script), q hangs waiting for input until thetimeoutabove fires. Don't useq -q < verify.q`
(stdin-redirect, no file arg) either — that mode parses each line as a
top-level expression and breaks multi-line function definitions.
The leading timeout -k 5 60 is load-bearing too, and it is the
only thing that works. A candidate or reference that never returns —
while[1b;...], or a join that goes quadratic on the 1000-row dummy —
pins a core at 100% until something kills it, and nothing else on this
path does: q's -T (command line or system "T") bounds IPC client
queries only, not a script file it is running; a q spinning in a tight
loop does not act on SIGTERM at all, which is what a plain timeout
sends; and the Bash tool does not kill a command that hits its 2-min
limit, it moves it to the background and leaves it running. All three
were measured. -k 5 follows the SIGTERM with SIGKILL five seconds
later, which q cannot ignore. timeout is GNU coreutils — present on
every Linux this project supports; on a box without it, drop the prefix
rather than let the verify fail on command not found.
Why a fresh directory, never fixed /tmp/verify*.q paths: two runs at once
(parallel agents, or two users on one host) would overwrite each other's files
between writing and loading, and the verify would then compare some other
case's code — silently. A file another user already created at a fixed path
cannot be overwritten at all. Both were seen in practice. Every path below is
therefore relative to the mktemp -d directory the block cds into.
Build verify.q in two passes: pass 1 concatenates four skill-
local .q files — verify_gen.q (gives NROWS0, NLIT0, typeGen,
parseSchema0, genTable0), literal_pool.q (.lit.fromFiles,
genTableLit), eval_describe.q (.eval.fmtCols + .eval.descVal +
.eval.isVacuous), eval_compare.q (.eval.cmp + .eval.flatNumeric
.eval.diag + .eval.wrapInfo). Pass 2 writes qwen's draft and the
reference to one file each, verify_qwen.q and verify_ref.q,
and appends the call-specific verification — all via single-quoted
heredocs so the backticks in q syms survive shell quoting.Why the draft and the reference live in their own files: the dummy tables
get extra rows drawn from the constants both of them name (dates, syms,
.z.d-1, ...), and .lit.fromFiles reads those constants out of the two
files before the tables are built. Without that, a filter on a value the
fixed pools lack — a 2030 date, `BTCUSD — is empty on both sides, and
empty compares equal to empty, so the verify reports a match it never
tested. Each file is then \l-loaded, which runs it exactly as the inline
code used to run.
Resolve those four files through $SKILL_ROOT as defined below —
never through a bare relative path, git rev-parse, or
$CLAUDE_PLUGIN_ROOT. This skill's directory is
${CLAUDE_SKILL_DIR}: Claude Code substitutes that exact token in
the SKILL.md text when the skill loads, in both of its homes (the
mcp-qsql-suggester repo, where it is a project-scope skill, and an
installed plugin). Nothing else works in both: CLAUDE_PLUGIN_ROOT is
not set in the Bash tool's shell and is not substituted in a
${CLAUDE_PLUGIN_ROOT:-...} spelling, a bare relative path assumes the
caller's cwd is the repo, and git rev-parse resolves to the user's
repo (or fails outside one) — the cat then fails with an error that
says nothing about paths. If the path in the line below is not an
absolute path (it still holds the unexpanded CLAUDE_SKILL_DIR
placeholder), substitution did not happen: use the "Base directory
for this skill" shown when the skill loaded instead.
Each Bash call gets a fresh shell, so every block below defines the
root it needs rather than relying on an earlier one.
SKILL_ROOT="${CLAUDE_SKILL_DIR}"
V=$(mktemp -d "${TMPDIR:-/tmp}/qsql-verify.XXXXXX") && cd "$V" || exit 1
{
cat "$SKILL_ROOT/verify_gen.q"
cat "$SKILL_ROOT/literal_pool.q"
cat "$SKILL_ROOT/eval_describe.q"
cat "$SKILL_ROOT/eval_compare.q"
} > verify.q
cat > verify_qwen.q <<'PYEOF'
qwen_result: <qwen q_code>;
PYEOF
cat > verify_ref.q <<'PYEOF'
reference_result: <reference q code from priority 1/2/3>;
PYEOF
cat >> verify.q <<'PYEOF'
system "S 42";
/ one entry per table_schemas entry: table name -> schema string
schemas:(enlist `trade)!enlist "`time`sym`price`size!`t`s`f`j";
lit:.lit.fromFiles[("verify_qwen.q";"verify_ref.q"); schemas];
{[lit;t;s] t set genTableLit[parseSchema0 s; NROWS0; NLIT0; lit]}[lit]'[key schemas; value schemas];
\l verify_qwen.q
\l verify_ref.q
strict: qwen_result ~ reference_result;
soft: .eval.cmp[qwen_result; reference_result];
vacuous: .eval.isVacuous[qwen_result] and .eval.isVacuous reference_result;
show `strict`soft`vacuous!(strict; soft; vacuous); / strict/soft: 11b = clean match; 01b = shape-wrap only; 00b = real divergence
if[(not strict) and not soft; .eval.diag[qwen_result; reference_result]];
if[(not strict) and soft; .eval.wrapInfo[qwen_result; reference_result]];
exit 0;
PYEOF
timeout -k 5 60 q verify.q -q </dev/null
The two-pass split is deliberate: pass 1 needs $SKILL_ROOT
interpolation (unquoted) for the four cat arguments; pass 2 needs
backtick protection (single-quoted heredoc) for q syms in the per-call
code. Building both into one quoted heredoc would block $SKILL_ROOT
interpolation; unquoted would let backticks trigger command
substitution. The { cat; cat; cat; cat; } > file pattern sidesteps both.
After pass 2, verify.q is a single q script that q parses
end-to-end, loading the two code files at the \l lines.
Note: load order matters — .eval.diag / .eval.wrapInfo (in eval_compare.q) call
.eval.descVal (in eval_describe.q), so eval_describe.q must
precede eval_compare.q in the cat sequence above; and literal_pool.q
must follow verify_gen.q, whose typeGen and 2h literal-row span it uses.
Verify dummy is tuned for grouped-query rigor (1000 rows, 3 syms
`AAPL`MSFT`GOOG, 2h timestamp span — each (sym, 5-min bucket)
cell carries ~14 rows on average; enough density for wavg / avg /
wsum divergences to surface). Gate-3 dummy (mcp_server/type_gen.q,
20 rows / 10 syms / 10h) is deliberately different — its purpose is
fast runtime safety on the server, not semantic-divergence detection
on the skill side. The two are intentionally decoupled. Both add the same
kind of literal rows (literal_pool.q, byte-identical in both places):
NLIT0 = 1000 here, inside the same 2h span, so a filter on a 2030 date
or a crypto sym finds rows at the density above rather than none.
strict vs softThe template emits a 2-bit verdict `strict`soft!(...) because the
two compares answer different questions:
strict = qwen_result ~ reference_result — q's exact deep-equality.
Strict on column order, keyed-vs-unkeyed wrap, type spelling.
soft = .eval.cmp[qwen_result; reference_result] — tolerant
equality from eval_compare.q. Treats column reorder, the
keyed/unkeyed wrap, renamed-but-positionally-identical columns, and
temporal columns that differ only in resolution as equivalent.
Implements the relation: same values, possibly different presentation.
The temporal axis is the newest and the least obvious, so: two columns
on the same resolution chain (p/z/t/v/u, or p/z/d/m)
are compared after casting the finer down to the coarser, which makes
a u minute-of-day bucket equal to the p timestamp bucket covering
the same minute. Different chains (d vs u) and n (a duration,
not a point in time) stay unequal. The coarser answer therefore wins
the comparison — accepted deliberately, because on the dummy table
p is single-day by construction and the defect this might hide
(5 xbar time.minute merging rows across days) changes the row count
and the aggregates, which are rejected on their own. eval_compare.q
has the full argument; note that mcp_server's copy deliberately
does not do this — clustering wants the disagreement.
Three meaningful outcomes (the fourth, strict=1b, soft=0b, is
impossible — strict implies soft):
strict | soft | meaning | classify as |
|---|---|---|---|
1b | 1b | clean match, identical bytes | Case B (no idiom note) |
0b | 1b | values agree but wrap differs (col reorder / keyed wrap / col rename / temporal resolution) | Case B + idiom note explaining the wrap difference — .eval.wrapInfo fires automatically |
0b | 0b | real semantic divergence | Case C — .eval.diag fires automatically |
Read vacuous first. vacuous=1b means both results are empty (or
all-null) even with the literal rows — so strict / soft compared nothing
with nothing, and a 11b there is not a match. Do not report case B on it:
render case A with "verification_unavailable": "vacuous_verify" (or
case D with the same field, on the rewrite path). Before settling for that,
check the reason is not yours — a schema string that does not match the
tables the code queries makes every result empty for a reason that is
fixable. If only ONE side is vacuous, vacuous is 0b and the compare is
real: that is case C, and .eval.diag's "likely empty filter" hint names
the side.
.eval.diag only fires on the third outcome (both 0b). It prints
both shapes, numeric ranges, magnitude ratio, and heuristic hints
pointing at the likely failure class (raw sum vs weighted avg, off-
by-one, null propagation, empty filter, column rename, etc). Use the
diag output to write divergence_symptom in the case-C JSON payload
— don't hand-inspect both results manually.
When strict=0b, soft=1b, the values match but the presentation
differs. This is not a Case C, but it is worth a one-line
idiom_note because the user may have expected a specific wrap (e.g.
keyed table when they ran select ... by sym).
.eval.wrapInfo fires automatically in this branch — read the axis
off its output rather than improvising an inspection. It prints meta
of both results, which names three of the four axes directly: column
order (the row order of the meta), column names, and the t column
for temporal resolution. The fourth, keyed-vs-unkeyed, is visible in
meta's key marking and in the results themselves. Non-table results fall back to
.eval.descVal, because meta raises 'type on them — and B-wrap is
genuinely reachable for bare atoms (1.0 vs 1.0000000001, 1 vs
1f, 09:05 vs a p).
Do not guess an axis you cannot point at: a B-wrap idiom_note is
required, and that requirement is exactly the pressure that produces
an invented explanation when the axis is not in front of you.
Diag does NOT run in this branch; its job is divergence diagnosis, not wrap diagnosis.
For the temporal axis specifically, the note should say what the two
types are and name the one thing that decides which the user wants —
e.g. "qwen's bucket is a u (minute-of-day); the reference's is a
p (timestamp). Same buckets on single-day data; if trade spans more
than one day you want the p form, since u merges the same
time-of-day across dates." That is a question about the user's data,
which is why it belongs in a note and not in a verdict downgrade.
Divergence = same input, different output. Both qwen and the
reference must run on identical dummy input in the same .q file. If they
produce different output on that shared input, that's divergence
(Case C). If qwen's code might fail on different inputs the user
did not ask about (multi-date when task is single-date; empty groups;
type variants) — that's fragility, not divergence. Do NOT
construct adversarial dummy data designed to expose fragility; the
dummy should mimic the data the user actually has. If you don't know
the shape, default to the sample dummy above without adversarial
tweaks. Fragility observations belong in **Idiom note**: (with
evidence the user's data may exhibit that shape — don't speculate),
not in verdict downgrade.
The skill's response is rendered by a Python formatter, not hand-written.
You decide which case fired and fill the free-text slots; the script handles
all headers, verdict skeletons, hedge clauses, and bullet formatting. Single
source of truth lives in .claude/skills/qsql-coder/scripts/format_output.py.
Two preamble blocks always render first: ### Instruction interpreted as
(your one or two clean sentences — light-cleanup the user's instruction
preserving intent; pass the cleaned version as the MCP instruction
argument too, since qwen was trained on clean instructions) and ### Schemas used (the table_schemas you passed to the MCP call, shown once at the
top).
Then pick the case from the MCP return + your verify outcome:
| case | when |
|---|---|
| A | passed=true; no Bash-verify triggered (no high-risk idiom, no functional form, winning_cluster_fraction >= 0.6 with no tie, no user reference — note this admits a plurality, so case A is no longer proof of unanimity) — or a trigger did fire but q is unreachable, in which case also set verification_unavailable: "no_q" so the verdict does not claim the trigger was absent — or Bash-verify ran and printed vacuous=1b, in which case set verification_unavailable: "vacuous_verify" |
| B | passed=true; Bash-verified; soft=1b (qwen's values match the reference). Two sub-cases:• B-clean — strict=1b: identical bytes; idiom_note optional.• B-wrap — strict=0b, soft=1b: values agree but col-order / keyed-wrap / col-name / temporal-resolution differ; idiom_note required to explain the wrap (.eval.wrapInfo prints both metas — read the axis off it). |
| C | passed=true; Bash-verified; strict=0b AND soft=0b (real divergence). .eval.diag ran automatically — read its output to write divergence_symptom. |
| D | passed=false; no self-consistency cluster survived gating |
For B and C, pick reference_priority:
Case C pre-flight: confirm qwen and the reference ran on identical input
in the verification .q file. If divergence emerged only after you changed
the dummy between runs, that's fragility on a different input shape, not
divergence on shared input — reclassify as case B (clean or B-wrap depending
on whether soft=1b on a shared-input rerun) and do NOT downgrade qwen's
verdict.
Case D sub-case: set opus_could_write true if you wrote and
Bash-verified an independent q version; false if the task is outside your
q knowledge or genuinely ambiguous (formatter then omits the SUGGESTED
CODE header and asks the user to refine).
Pipe the JSON payload directly into the formatter via a single-quoted
heredoc. Single quotes around the delimiter disable shell expansion, so
q code's backticks (`time, `sym, …) survive verbatim — same
protection the Bash-verify protocol relies on. The delimiter is
__QSQL_FORMAT_END__ (more unique than JSONEOF) to avoid the unlikely
case that q code contains a line equal to the sentinel.
No temp file: heredoc goes straight to the script's stdin, so multiple parallel invocations (e.g. spawning 5 agents to render 5 cases at once) don't race on a shared path.
python3 "${CLAUDE_SKILL_DIR}/scripts/format_output.py" <<'__QSQL_FORMAT_END__'
{
"instruction_interpreted": "<one or two sentences>",
"schemas": {"trade": "`time`sym`price`size!`p`s`f`j"},
"case": "A", // A | B | C | D
"qwen_code": "<q code from MCP>",
"passed": true, // true for A/B/C; false for D
"rounds_used": 1,
"candidates_generated": 4,
"winning_cluster_size": 4,
"winning_result_vacuous": false, // copy the MCP's field verbatim
"lint_gate": "kx_qlint_c9", // copy the MCP's field verbatim; when it is
// "disabled" the verdict says so, because the
// server had no usable qlint.q_ and filtered
// on parse + execution only
"reference_priority": null, // null for A/D; 1|2|3 for B/C
"reference_source_label": null, // free text e.g. "the user-provided reference"
"verify_shape": null, // e.g. "20 rows x 3 cols"
"divergence_symptom": null, // one sentence — case C only
"suggested_code": null, // q code — case C, and case D when opus_could_write
"final_issues": null, // list[str] — case D only
"opus_could_write": null, // bool — case D only
"basis_label": null, // free text e.g. "the instruction plus schema" — case D1 only
"verification_unavailable": null, // null | "no_q" | "vacuous_verify" — case A and D only.
// Replaces the verdict's reason clause when
// the reference check was IMPOSSIBLE rather
// than unnecessary. "no_q" for the
// unreachable-q path above, "vacuous_verify"
// when Bash-verify printed vacuous=1b; the
// sibling skill owns the other value
// ("quick_mode").
// Rejected on cases B and C, which are the
// verified cases by definition.
"idiom_note": null // optional one sentence; null = omit line
}
__QSQL_FORMAT_END__
The stdout IS the response — relay it verbatim to the user.
Free-text slots that you author: instruction_interpreted,
reference_source_label, divergence_symptom, basis_label, idiom_note.
Everything else (### headers, verdict skeleton, priority-3 hedge,
schema bullets, code fences) is script-rendered.
reference_source_label must read grammatically after "Bash-verified against"
(case B) and "diverged from" (case C). Include the article: e.g. "the
user-provided reference", "the literal-translated formula from the
instruction", "my own independent translation".
| case | required (in addition to base) |
|---|---|
| A | qwen_code, passed=true, rounds_used, candidates_generated, winning_cluster_size, lint_gate |
B-clean (strict=1b) | + reference_priority ∈ {1,2,3}, reference_source_label, verify_shape |
B-wrap (strict=0b, soft=1b) | + reference_priority, reference_source_label, verify_shape, idiom_note (required) — describe the wrap axis (col order / keyed wrap / col name / temporal resolution), naming it from the meta pair .eval.wrapInfo printed |
C (both 0b) | + reference_priority, reference_source_label, verify_shape, divergence_symptom, suggested_code |
| D | + final_issues (list), opus_could_write (bool); if opus_could_write=true: + suggested_code, basis_label |
verification_unavailable is required on either case whenever a
Bash-verify trigger fired and q was unreachable ("no_q"), or the verify
ran and printed vacuous=1b ("vacuous_verify") — case A because its reason
list would otherwise deny the trigger, case D because its fallback sentence
would otherwise blame the instruction. It is optional (and meaningless)
anywhere else.
suggested_code must be verbatim verified codesuggested_code must be byte-for-byte the q you ran in the verify
.q file. No rewrites — even cosmetic ones can cross q eval-order
boundaries. Want a different shape? Re-verify it first.
If the formatter exits non-zero (validation error, invalid JSON), surface the stderr message to the user and ask which field to correct. Do NOT fall back to writing the Markdown yourself — the whole point is that the script is single source of truth. Free-form fallback re-opens the drift bug we just fixed.
| Header | Source | Meaning |
|---|---|---|
TOOL CODE (suggested) | qwen via MCP | Use this; no verification needed |
TOOL CODE (suggested, verified) | qwen via MCP | Use this; Bash-verified |
TOOL CODE (not suggested) | qwen via MCP | Don't use this; shown for context |
TOOL CODE (failed) | qwen via MCP (no cluster survived gating) | Don't use; shown for transparency |
SUGGESTED CODE (Provided Reference) | user (priority 1, q code from user's original message echoed back) | Use this — your provided reference matches expected result; qwen diverged from it |
SUGGESTED CODE (generated) | you (priority 2 literal-formula / priority 3 own translation) | Use this — wrote and verified because qwen diverged |
SUGGESTED CODE (without MCP Tool) | you | Use this — qwen failed entirely |
passed=true means "the q ran without
raising", NOT "the q computes the intended answer". Semantic intent
failures (e.g. wrong aggregate idiom, value off by an order of
magnitude) escape every static and runtime gate; only Bash-verify
against an independent reference catches them.${CLAUDE_SKILL_DIR}/pre-derive.md, the file sitting next to this
SKILL.md, that injects an
Expected result schema: hint into qwen's prompt, aligning the MCP
path with the prompt format used during model evaluation (the hint
was never in the training data).
It is not auto-loaded and not part of the customer flow.
Apply it only when the developer explicitly requests pre-derive
mode (e.g. "use pre-derive mode" / "read pre-derive.md and follow
it"); then Read that file and follow its preconditions + Bash
template.**Idiom note**: only with evidence the
user's data exhibits that shape; otherwise omit. Speculating about
unseen inputs is a known source of false Case C verdicts.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub kxsystems/mcp-qsql-suggester --plugin mcp-qsql-suggester2 skills in this plugin
Other plugins' skills for the same job