Skip to content

Fix five matrix-harness defects that corrupt or block scoring - #2282

Merged
malibio merged 4 commits into
mainfrom
issue-2239-harness-fixes
Aug 24, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2239-harness-fixes

Conversation

@malibio

@malibio malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator

Five defects in the matrix eval harness, found while re-running #2239. No product code changes — every fix is in scripts/eval/.

Closes #2263.

1. Nested properties were never matched

The daemon serialises typed properties under the node's own type key, and toSnapshotNode passed that wrapper through untouched. Every consumer asks about the INNER keys, so keyed lookups found nothing and populatedCount always returned 1 (the wrapper) — making minProperties: 2 unsatisfiable by construction.

Measured against DeepSeek V4 Pro: scenarios 9, 10b and 13 each failed 3/3 reps on writes that persisted exactly what was asked. The trajectory verdicts corroborate independently — 21 outcome/trajectory disagreements across three reps, every one in the same direction (trajectory PASS, outcome FAIL). Model error would produce a mix.

flattenTypeKeyedProperties lifts the wrapper once at the snapshot boundary, so matching, counting and the failure messages cannot drift apart.

The bug only penalised typed nodes with nested properties, so it was non-uniform across models — every score on #2239 is depressed by an unknown, model-dependent amount.

2. The preflight gate could never pass

Numerator and denominator sat on opposite sides of should_skip_scope_filter: a real query is scope-filtered (skill isn't in the Knowledge allowlist → always 0) while an enumerate gets the bypass (→ 8). The gate reported 0/8 against a warm, fully-embedded index and exited 2 before any scenario ran, for every model.

Switching to an enumerate isn't the fix — enumerate_nodes never consults embeddings, so it would wave through the cold-index state the gate exists to catch. embeddedSkillCount reads the embedding table via the daemon's own reported DB path, and fails closed.

3. Failed setups cascaded into scored failures

Dependent scenarios now excluded rather than scored, with a Blocked: summary line so the denominator never shrinks unexplained.

4. Scenario 12a could not establish 12d's state

12a set up a type tracking only estimated_days; 12d then asked for a sign-off field that was never declared. The model reasoned correctly and declined to invent it — scored red by the fixture. 12a now names the field, as scenario 3 does (#1846).

5. The uniformity guard discarded a legitimate full pass

Second commit. With (1) fixed, DeepSeek scored 21/21 — and the guard called it a harness signature and wrote no results file. Its premise ("real runs have never been perfectly uniform") held only while the scoring bug suppressed passes.

The guard has caught two real false results, so deleting it is wrong. It now takes a distinct-tool count and exempts a full pass with genuine diversity; a uniform zero stays suspicious regardless, since both known false results were all-fail.

Verification

bun run test:scripts: 250 pass, 0 fail (was 224).

Both fixes were confirmed to FAIL before being checked in — 4 tests for the nested-property fix, 1 for the uniformity exemption — asserting scoring outcomes on real daemon-shaped payloads rather than helper return values. Cold-index cases are pinned in both directions, so a probe that always returns the seed count fails just as a structurally-zero one does.

Pre-push gate passed in full.

🤖 Generated with Claude Code

https://claude.ai/code/session_01S1ztc8m23p4WHoSToNfm89

malibio and others added 2 commits August 24, 2026 15:45
…t gate pass

Four defects in the matrix harness, all of which corrupt or block scoring. No
product code changes; every fix is in scripts/eval/.

## Nested properties were never matched

The daemon serialises typed properties under the node's own type key:

    {"task": {"_schema_version": 1, "due_date": "2026-08-06", "status": "open"}}

`toSnapshotNode` passed that wrapper through untouched, and every consumer -
`nodeSatisfies`, `populatedCount`, and both failure renderers - asks about the
INNER keys. So a keyed lookup found nothing and `populatedCount` returned 1
(the wrapper) no matter how many fields were written, making `minProperties: 2`
unsatisfiable by construction.

Measured against DeepSeek V4 Pro on d393ad1, scenarios 9, 10b and 13 each
failed 3/3 reps on writes that persisted exactly what was asked:

    x 9. Set property on existing node    tools=[update_node]
      -> no existing node was updated to match [content~"offline sync",
         some property = 8]
      - nodes modified: feature_write_up:"Offline sync"
        {feature_write_up={"_schema_version":1,"estimated_days":8,...}}

The trajectory verdicts corroborate this independently: across three reps there
are 21 outcome/trajectory disagreements and every one runs the same direction
(trajectory PASS, outcome FAIL). Model error would produce a mix.

`flattenTypeKeyedProperties` lifts the wrapper once, at the snapshot boundary,
so matching, counting and the failure messages cannot drift apart. Only the
node's own type key is lifted, only when it holds an object, and keys sitting
beside the wrapper survive. `_schema_version` is dropped so `minProperties`
counts what the model wrote rather than what persistence added.

The bug was not uniform across models - it only penalises typed nodes with
nested properties - so every score recorded on #2239 is depressed by an unknown,
model-dependent amount and the cross-model ranking there is not decision-grade
until the arms are re-run.

## The preflight skill-index gate could never pass

`awaitSkillIndex` compared a numerator and denominator sitting on opposite sides
of `should_skip_scope_filter` (packages/core/src/ops/search_ops.rs):

    search "update an existing node" --type skill  -> always 0 (scope-filtered;
                                                      `skill` is not in the
                                                      Knowledge allowlist)
    search ""                        --type skill  -> 8 (enumerate; bypass applies)

so it reported 0/8 against a warm, fully-embedded index, waited its full 120s
timeout and exited 2 before any scenario ran - for every model. preflight.ts
shipped in d393ad1 and has never completed a successful run.

Switching the numerator to an enumerate is not the fix: `enumerate_nodes` queries
rows by type and never consults embeddings, so it returns every skill the instant
the daemon boots and would wave through the cold-index state the gate exists to
catch. The CLI exposes no `--scope` override, so no CLI query can answer the
question. `embeddedSkillCount` reads the embedding table directly, via the
daemon's own reported database path so it cannot drift onto a different database
than the one being scored, and fails closed (0, never a fallback count) when the
query cannot run.

## Scenarios whose setup failed were scored as model failures

Setup turns are graded with the same matcher, so a correct setup was marked
failed - and the harness then ran the dependent scenario anyway after printing
its own warning that the result was meaningless. 12d failed 2/3 reps that way.
Those scenarios are now excluded rather than scored, with a `Blocked:` summary
line so the denominator never shrinks with nothing on screen to explain it.

## Scenario 12a could not establish the state 12d asserts

12a's prompt set up a type tracking only `estimated_days`, and 12d then asked
for the biggest job to be marked signed off - a field the type never declared.
The model reasoned correctly and declined to invent it:

    "The biggest job is search indexer at 21 days, but the Build Job type only
     tracks estimated_days - it has no 'signed off' field."

That is the behaviour this suite wants, scored red by the fixture. 12a now names
the sign-off field too, the same way scenario 3 names its downstream fields
(#1846). The fixture's own comment predicted this failure mode for this group.

## Verification

`bun run test:scripts`: 245 pass, 0 fail (was 224). The nested-property tests
were confirmed to FAIL (4 of them) against the unfixed flattening before being
checked in against the fix - the assertion is on the scoring outcome for real
daemon-shaped payloads, not on a helper's return value. The preflight tests
cover the cold-index case in both directions, so a probe that always returns the
seed count fails just as a structurally-zero one does.

`rust:lint` fails in this worktree on a missing `resources/skill/**/*` glob. That
is pre-existing - it reproduces in the primary checkout, and this change touches
no .rs files.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1ztc8m23p4WHoSToNfm89
The guard aborts a run whose scored scenarios are uniformly 0% or 100%, on the
stated premise that "real runs on this suite have never been perfectly uniform".
That premise held only while outcome scoring mis-read type-keyed properties and
red-lined correct writes. With the preceding commit's fix in place a capable
model legitimately passes everything: DeepSeek V4 Pro scored 21/21, the guard
called it a harness signature, and no results file was written - the data was
simply lost.

This is the failure mode of a heuristic calibrated against a broken baseline: it
fires exactly when the thing it was measuring starts working.

Deleting the guard is the wrong answer - it has caught two real false results
(a contaminated 11/12, and negative assertions scoring green while every turn
died on context overflow). What separates those from a real full pass is
observable without a model in the loop: a degenerate environment produces
identical turns that call nothing, while a run that actually exercised the suite
calls many different tools. `checkUniformity` now takes the distinct-tool count
and exempts a full pass that clears MIN_DISTINCT_TOOLS_FOR_REAL_PASS (3, chosen
below the suite's real diversity and above what a stuck run can produce).

A uniform ZERO stays suspicious regardless of diversity: both known false
results were all-fail, and a model calling varied tools while failing every
scenario is precisely the "same unhandled code path" case the guard describes.

The parameter defaults to 0, so any caller that does not measure diversity keeps
today's strict behaviour rather than silently getting the looser check.

Verified: `bun run test:scripts` 250 pass, 0 fail (was 245). The new tests were
confirmed to FAIL against the unfixed guard before being checked in - one fails
on the exemption path, and the remaining four pin the shapes that must still
abort (near-zero diversity, uniform zero, omitted argument).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1ztc8m23p4WHoSToNfm89
@malibio

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2282

Review Type: Initial review (comprehensive)
Scope: 2 commits, 8 files, all confined to scripts/eval/. No product code, no .rs files.
Closes: #2263


Summary

This is a genuinely high-quality diagnostic PR. All four defects are real, correctly root-caused, and the fixes address the cause rather than the symptom. The standout is that the author identified and rejected the obvious fix in two places — swapping the preflight numerator to an enumerate (which would make the gate vacuous), and deleting the uniformity guard (which has caught two real false results) — and documented why. That reasoning is preserved in the code comments, not just the commit message, which is where it will actually be read.

I independently re-verified the author's central claims rather than taking them on trust:

  • bun run test:scripts → 250 pass, 0 fail. Confirmed.
  • Reverted flattenTypeKeyedProperties at the call site (const props = rawProps) and re-ran end-state.test.ts → 4 tests fail. The regression tests are real and genuinely load-bearing, and they assert scoring outcomes (nodeSatisfies verdicts on daemon-shaped payloads), not helper return values. This was the pattern the author flagged as previously gotten wrong; it is right here.
  • Confirmed _schema_version is genuine daemon bookkeeping and not model-written — packages/core/src/db/sqlite_store/nodes.rs:1359 writes it, and packages/core/src/playbook/cel.rs:198 already calls it an internal field to skip. Excluding it aligns the harness with existing product semantics rather than inventing a harness-local convention.
  • Exercised the flattening edge cases directly (collision, array, null, coincidental name match). All behave correctly — see the detailed finding below.

I found one issue worth fixing before merge, plus several smaller items. Net assessment: this is a clear improvement to code health and the analysis quality is well above the bar.


Requirements Check against #2263

Acceptance criterion Status
Property matching unwraps the type key before comparison ✅ flattenTypeKeyedProperties, applied once at the snapshot boundary
_schema_version excluded from populatedCount ✅ via PERSISTENCE_KEYS
Regression test: nested write satisfies minProperties: 2 and a keyed properties assertion ✅ both covered, and both verified to fail without the fix
Preflight probe asserts embedding presence, not row existence ✅ embeddedSkillCount joins node → embedding
Test covering the cold-index case, so a vacuous gate cannot regress unnoticed ✅ covers 0, partial (5), and warm (8) — both directions
Scenarios whose setup did not verify are excluded rather than scored ✅ excludedAsSetupFailed + Blocked: summary line
NS_SKILL_INDEX_PROBE_DB stopgap removed ✅ N/A — verified it was never committed to main (git grep origin/main finds nothing); it was a local-only patch, so there is nothing to remove
#2239 arms re-run after the fix ⏳ Out of scope for this PR — follow-up work
Pre-fix scores on #2239 annotated as unreliable ⏳ Out of scope for this PR — follow-up work

Bonus beyond the issue: fixture 12a and the uniformity-guard exemption, both of which were discovered downstream of the primary fix. The 12a change is well-justified — the model's refusal to invent an undeclared field was correct behavior being scored red.


Code Review Findings

🔴 Critical

📁 scripts/eval/preflight.ts:310-329 — embeddedSkillCount does not fail closed when sqlite3 is absent; it throws.

The docstring states the function "Returns 0 — never a fallback count — when the query cannot be run at all". That contract holds for a failing query but not for a missing binary. I verified the actual behaviour:

Bun.spawnSync(["sqlite3-definitely-not-installed", ...])
  → THREW: Error: Executable not found in $PATH

Bun.spawnSync throws on a missing executable rather than returning a non-zero exitCode. The guard only covers if (r.exitCode !== 0) return 0;, so the throw escapes. Tracing the call path:

embeddedSkillCount → retrievableSkillCount → awaitSkillIndex → gate() (runner.ts:784-802), where:

} catch (e) {
  if (e instanceof EnvironmentError) abortOnEnvironment(fixture.name, e);
  throw e;
}

A plain Error is not an EnvironmentError, so it is rethrown as an unhandled exception. A machine without sqlite3 on PATH gets a raw stack trace instead of the harness's actionable environment diagnostic — on a harness whose entire design philosophy is "distinguish environment faults from model failures". This is the exact failure class the surrounding code works hard to avoid.

This is also a new hard runtime dependency. The docstring justifies it with "sqlite3 is already required by the harness's own diagnostics", but that claim does not hold: the only other sqlite3 occurrences in scripts/eval/ are at preflight.ts:263 and preflight.ts:401, and both are text inside remediation messages — commands printed for a human to run, never executed. This PR introduces the first programmatic dependency on the sqlite3 binary, and the comment asserting otherwise will mislead the next reader.

Principle — fail-safe defaults / honest contracts: a function documenting "fails closed" must fail closed on every path that can prevent the query running, not just the anticipated one. A guard that covers one of two failure modes is more dangerous than no guard, because it invites reliance on a property that does not hold.

Suggested fix — wrap the spawn and make the dependency explicit:

export function embeddedSkillCount(
  dbPath: string,
  run: (db: string) => { exitCode: number | null; stdout: string } = (db) => {
    try {
      const r = Bun.spawnSync([...], { ... });
      return { exitCode: r.exitCode, stdout: r.stdout.toString() };
    } catch {
      // `sqlite3` absent from PATH: spawnSync THROWS rather than returning a
      // non-zero exit. Fail closed like any other unusable probe.
      return { exitCode: null, stdout: "" };
    }
  },
): number {

The existing test expect(embeddedSkillCount("/db", () => ({ exitCode: null, stdout: "" }))).toBe(0) already pins the desired outcome — it just never reaches this path because the injected fake cannot throw. Worth adding one case with a run that throws, so the contract is tested rather than assumed.

Separately, consider a preflight check that sqlite3 resolves, raising an EnvironmentError naming the missing binary. That converts a stack trace into the actionable message the harness's other gates all produce.

🟡 Improvements

📁 scripts/eval/graph.ts:124 — orphaned JSDoc.

The comment /** Narrow one CLI node object into a SnapshotNode, tolerating absent fields. */ was left in place while the new declarations were inserted directly beneath it, so it now sits immediately above PERSISTENCE_KEYS, ~57 lines from the toSnapshotNode it documents (now at line 181):

/** Narrow one CLI node object into a SnapshotNode, tolerating absent fields. */
/**
 * Bookkeeping keys the daemon writes itself...
 */
const PERSISTENCE_KEYS = new Set(["_schema_version"]);

Two adjacent doc comments describing unrelated things. Move it back down to toSnapshotNode.

Principle: a doc comment's position is part of its meaning — a misattached one actively misinforms, unlike a missing one.

📁 scripts/eval/graph.ts:359-361 (diffSnapshots) — flattening silently changes change-detection, which is unexamined.

stableStringify now compares flattened properties, so _schema_version no longer participates in changedNodes. I verified this:

changedNodes on a _schema_version-only bump: 0   (was 1 before this change)

I believe this is correct and arguably an improvement — expectNoWrites should not red-line a read scenario because persistence bumped a schema version the model never touched. But it is a real behavioural change to the one comparator that expectNoWrites depends on, and the file itself flags that path as safety-critical:

"this is the only comparator behind changedNodes, and changedNodes is what expectNoWrites reads, making it one of the few places a false PASS could originate."

Given that standing warning, this deserves an explicit note and a test pinning the intent, rather than arriving as an undocumented side effect. If a migration bumps _schema_version on nodes a read scenario touched, that turn now passes expectNoWrites where it previously failed — desirable, but it should be a decision on the record.

📁 scripts/eval/graph.ts:170-171 — wrapper contents shadow sibling keys on collision.

Verified behaviour:

{ task: { status: "inner" }, status: "sibling" }  →  { status: "inner" }

The spread order means the wrapper wins and the sibling is silently dropped. Every other edge case is handled well and I confirmed each:

input result assessment
wrapper is an array left wrapped ✅ correct, guarded by !Array.isArray
wrapper is null left wrapped ✅ correct
node_type coincides with a property name unwrapped ⚠️ inherent ambiguity, correctly tested at end-state.test.ts:651
_schema_version as a flat sibling dropped ✅ correct

The collision case is almost certainly unreachable given how the daemon serialises, and the comment explicitly reasons about preserving siblings — so this is not a correctness objection so much as an unstated precedence rule. Worth one line documenting which side wins, since "keys beside the wrapper must survive" is stated as the goal and a colliding sibling is the one case where it does not.

📁 scripts/eval/preflight.ts:296-301 — retrievableSkillCount retains a now-unused parameter.

function retrievableSkillCount(env: EvalEnv, _limit: number): number {
  return embeddedSkillCount(readServedDatabasePath(env));
}

_limit is dead, and the sole caller (awaitSkillIndex's default probe) passes expected into it. The function is now a thin adapter with a vestigial signature. Dropping the parameter and updating the one call site would be cleaner — and per this repo's stated no-backward-compatibility posture, there is no reason to keep it.

Also note retrievableSkillCount calls readServedDatabasePath(env) on every poll — once per 3s for up to 120s, i.e. up to ~40 CLI subprocess spawns to re-read a path that cannot change during the wait. Hoisting it above the loop in awaitSkillIndex would be both faster and more obviously correct. Minor, since the wait is already dominated by the 30s embedding debounce.

📁 scripts/eval/runner.ts:557 — MIN_DISTINCT_TOOLS_FOR_REAL_PASS = 3 is defensible but untested at the boundary.

The threshold is well-justified in prose (below the suite's real diversity, above what a stuck run produces) and the distinctToolsCalled = 0 default is the right call — an omitted argument keeps the strict pre-existing behaviour rather than silently loosening the check. That is a genuinely good API decision.

The tests cover 0, 1, and 6 but not the boundary itself. I verified it directly:

21/21 diversity=3 → ACCEPTED
21/21 diversity=2 → flagged

Correct, but the constant could be changed to 4 and every existing test would still pass. A test at exactly 3 and exactly 2 would pin the threshold rather than leaving it inferable only from the constant's own value.

Principle: a magic threshold's tests should straddle it, or the value is not actually pinned by the suite.

📁 scripts/eval/runner.ts:1270-1272 — diversity is measured over scored only, which now excludes setup-failed scenarios.

distinctToolsCalled is computed from scored, and partitionExcluded now removes excludedAsSetupFailed entries from that set. So the two changes in this PR interact: a run where many groups' setups fail both shrinks the scored denominator and narrows the tool surface the guard sees.

This is the conservative direction (less diversity → more likely to flag), so it does not create a false-pass risk. Worth a sentence acknowledging the interaction, since the two features landed in separate commits and their coupling is not obvious from either one alone.

🟢 Nitpicks

  • Nit: 📁 scripts/eval/preflight.ts:328 — Number.parseInt(...) || 0 coerces a legitimate 0 through the || fallback to 0. Harmless here since both mean "not ready", but it also maps "-3" → -3 and "1e3" → 1. sqlite3 COUNT() cannot produce either, so this is purely stylistic; Number.isFinite + explicit check would express intent more precisely.
  • Nit: 📁 scripts/eval/graph.ts:176-179 — the local omit helper is a one-off; delete merged[nodeType] after the spread would avoid the extra function and the intermediate object. Current form is arguably clearer about intent, so take or leave.
  • Nit: 📁 scripts/eval/fixtures/agent-matrix.ts:1421 — the 12a prompt is now a three-clause sentence ("...we take on, roughly how many days each needs, and whether each one is signed off"). Justified and well-explained, but each added clause makes the prompt slightly less like something a user would actually type, which is a mild threat to the suite's ecological validity. Worth watching as a trend across fixtures rather than changing here.
  • Nit: scripts/ is not covered by quality:fix/quality:check (both target packages/), so these files get no lint enforcement. Not introduced by this PR, but relevant context for a directory that is steadily accruing real logic.

What this PR does well

Calling these out because they are the parts worth repeating:

  • The fix is applied at the boundary, not at each call site. Flattening once in toSnapshotNode means matching, counting and the failure renderers cannot drift apart — I confirmed renderNodes reads the same flattened n.properties, so failure output now shows exactly the keys the matcher used. Fixing this in nodeSatisfies alone would have left the failure messages lying.
  • The rejected fixes are documented. Both "why not swap the numerator to an enumerate" and "why not delete the uniformity guard" are recorded in the code. The next person to look at that gate will not re-derive the vacuous version.
  • Evidence-driven diagnosis. The observation that all 21 outcome/trajectory disagreements ran the same direction (trajectory PASS, outcome FAIL) is exactly the right signal — model error would produce a mix. That is what separates a harness bug from a model regression.
  • The uniformity guard's parameter default is right. Defaulting distinctToolsCalled to 0 means an un-updated caller keeps the strict check instead of silently getting the looser one. Easy to get backwards; got it right.
  • Honest scope discipline. No product code touched, and the pre-existing rust:lint failure was correctly identified as unrelated rather than papered over.

Recommendation

APPROVE — with the 🔴 finding addressed before merge.

The sqlite3-missing throw is a small, contained fix (a try/catch in the default run closure plus a test that injects a throwing probe), and it is worth doing because it undermines a contract the docstring explicitly advertises and lands on the harness's environment-vs-model boundary. Everything else is polish that can follow.

The core work is correct, well-tested, and the regression tests are the real thing — I confirmed they fail against the unfixed code and that they assert scoring outcomes on realistic daemon payloads rather than helper return values. This is a clear net improvement to a harness whose defects were silently corrupting every score recorded on #2239.

One follow-up worth tracking separately: the remaining two acceptance criteria on #2263 (re-run the #2239 arms; annotate the pre-fix scores as unreliable) are correctly out of scope here, but the cross-model ranking on #2239 stays non-decision-grade until they are done.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (with one 🔴 to address before merge — posted as a comment because GitHub blocks self-approval). Full findings in the review comment above.

Headline: embeddedSkillCount does not fail closed when sqlite3 is missing from PATH — Bun.spawnSync throws rather than returning a non-zero exitCode, so the throw escapes gate() as a non-EnvironmentError and surfaces as a raw stack trace. Verified empirically. Small contained fix.

Independently re-verified: 250 pass/0 fail; the 4 nested-property tests confirmed to fail against reverted flattening; regression tests assert scoring outcomes on real daemon payloads, not helper return values.

## Critical: the fail-closed contract did not hold for a missing binary

`embeddedSkillCount`'s docstring promises it returns 0 "when the query cannot be
run at all". That held for a query that FAILS but not for one that cannot start:
`Bun.spawnSync` throws on a missing executable rather than returning a non-zero
`exitCode`, so the `exitCode !== 0` guard was never reached. The throw escaped
through `awaitSkillIndex` into `gate()`, which renders only `EnvironmentError`
actionably and rethrows anything else as a raw stack trace — landing on exactly
the environment-vs-model boundary this gate exists to police.

The whole probe call is now wrapped, not just the default closure, so an
injected probe that throws is covered too. The existing
`exitCode: null` test already pinned the desired outcome but could never reach
this path, because an injected fake cannot throw; the new test injects one that
does, and was confirmed to FAIL against the unwrapped call.

The docstring's claim that "sqlite3 is already required by the harness's own
diagnostics" was also wrong, and is corrected: the other mentions of sqlite3 in
that file are remediation TEXT printed for a human, never executed. This is the
first place the harness runs it, so the dependency is now stated plainly.

## Also addressed

- `changedNodes` behaviour change is documented and pinned. Flattening dropped
  `_schema_version` from the comparator behind `expectNoWrites`, so a node whose
  only difference is a persistence-bumped schema version no longer counts as
  changed. That is the intended direction, but it loosened a false-PASS path as
  an undocumented side effect. Three tests now pin both directions — a version-
  only bump is not a change, a real field change still is, including alongside a
  bump — so the loosening cannot widen unnoticed. Built through `toSnapshotNode`
  rather than the `node()` helper, which constructs a SnapshotNode directly and
  would not exercise flattening at all.

- Collision precedence stated. On `{task: {status: "inner"}, status: "outer"}`
  the wrapper wins. Unreachable given current daemon serialization, so the rule
  is stated rather than defended, and pinned by a test.

- Orphaned JSDoc moved back onto `toSnapshotNode`, ~57 lines from where the new
  declarations had stranded it above `PERSISTENCE_KEYS`.

- Dead `_limit` parameter dropped from `retrievableSkillCount` and its one call
  site.

- Threshold boundary tests added at exactly 3 and 2. The previous cases (0, 1, 6)
  left `MIN_DISTINCT_TOOLS_FOR_REAL_PASS` changeable to 4 with every test still
  passing, so the constant was not actually pinned by the suite.

## Skipped, with reasons

- `Number.parseInt(...) || 0` (nit): reviewer notes `sqlite3 COUNT()` cannot
  produce the inputs that would differ, and 0 is the correct result for every
  case it maps. Purely stylistic; changing it adds no behaviour.
- Replacing the local `omit` helper with `delete` after the spread (nit):
  reviewer called the current form "arguably clearer about intent". Agreed.
- 12a prompt length (nit): the three-clause form is what makes 12d winnable,
  which is the defect it was changed to fix.
- Hoisting `readServedDatabasePath` out of the poll loop: ~40 subprocess spawns
  across a wait already dominated by a 30s embedding debounce. Real but
  immaterial, and moving it changes the shape of `awaitSkillIndex`'s injectable
  probe, which is load-bearing for its tests. Worth revisiting if the gate is
  ever refactored.

Verified: `bun run test:scripts` 257 pass, 0 fail (was 250). Both new guards
confirmed to FAIL against the unfixed code before being checked in — the
throwing-probe test against the unwrapped call, and 2 of the changedNodes tests
against a `PERSISTENCE_KEYS` removal that never runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1ztc8m23p4WHoSToNfm89
@malibio

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — fee42ac4

5 addressed, 4 skipped. Tests: 257 pass, 0 fail (was 250).

🔴 Critical — fixed

embeddedSkillCount now fails closed on a missing sqlite3. The finding was correct and the diagnosis exact: Bun.spawnSync throws on a missing executable rather than returning a non-zero exitCode, so the guard was never reached and the throw escaped into gate() as a raw stack trace — on the environment-vs-model boundary the gate exists to police.

Wrapped the whole probe call rather than just the default closure, so an injected probe that throws is covered too. You noted the existing exitCode: null test already pinned the outcome but could never reach the path; the new test injects a throwing probe and was confirmed to fail against the unwrapped call.

Also corrected the docstring's false claim that "sqlite3 is already required by the harness's own diagnostics" — you were right that those mentions are remediation text printed for humans, never executed. The dependency is now stated plainly.

🟡 Addressed (4)

  • changedNodes behaviour change — documented on stableStringify and pinned by three tests: a version-only bump is not a change, a real field change still is, including alongside a bump. Built through toSnapshotNode rather than the node() helper, which constructs a SnapshotNode directly and would not exercise flattening at all. 2 of the 3 confirmed to fail against a disabled PERSISTENCE_KEYS removal.
  • Collision precedence — stated (wrapper wins) and pinned by a test.
  • Orphaned JSDoc — moved back onto toSnapshotNode.
  • Dead _limit param — dropped, with its call site.
  • Threshold boundary — tests at exactly 3 and 2. You were right that the constant could have changed to 4 with every prior test passing.

⏭️ Skipped (4)

  • parseInt(...) || 0 — you noted sqlite3 COUNT() cannot produce the differing inputs, and 0 is correct for every case it maps. Stylistic.
  • omit helper → delete — you called the current form "arguably clearer about intent". Agreed.
  • 12a prompt length — the three-clause form is what makes 12d winnable, which is the defect it fixes.
  • Hoisting readServedDatabasePath — real, but ~40 spawns across a wait dominated by a 30s embedding debounce, and moving it changes the shape of awaitSkillIndex's injectable probe, which is load-bearing for its tests. Worth revisiting if the gate is refactored.

Note on the NS_SKILL_INDEX_PROBE_DB AC

Confirmed independently — it was a local-only stopgap, never committed to main, so there is nothing to remove. Your git grep origin/main check matches mine.

Not addressed here (out of scope)

scripts/ being outside both quality:fix and quality:check is a real gap and worth its own issue — it is a repo-wide tooling change, not something this PR should introduce.

Pre-push gate passed in full.

@malibio

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2282

Review Type: Re-Review
Scope of this pass: fee42ac4 only (delta a2b00f6f..HEAD) — 5 files, +126/−5, all in scripts/eval/.
Closes: #2263


Previous Review Summary

Count
Recommendations in prior review 11 (1 🔴, 6 🟡, 4 🟢)
Addressed 6 (the 🔴 + 5 🟡)
Consciously skipped, with reasons 4 (3 🟢 nits + 1 🟡 perf)
Deferred out of scope 1 (scripts/ outside quality:*)
New issues found in fee42ac4 1 🟢

Every claim in the author's response was re-verified independently rather than taken on trust. All of them hold, including the two the author flagged as traps. Details below.


Verification I performed

I did not accept the author's test-failure claims; I reproduced each by reverting the fix and re-running, then restored. git status is clean of all verification edits (only a pre-existing unrelated Cargo.lock modification remains).

1. Suite count — confirmed.

bun run test:scripts → 257 pass, 0 fail  (was 250)

2. The throwing-probe test genuinely fails against the unwrapped call — confirmed.
Reverted the try/catch back to const r = run(dbPath);:

(fail) embeddedSkillCount > fails closed when the probe THROWS
 20 pass, 1 fail

The error surfaces exactly as the prior review predicted — an uncaught Error: Executable not found in $PATH escaping through embeddedSkillCount.

3. The underlying Bun.spawnSync behaviour — re-confirmed empirically.

Bun.spawnSync(["sqlite3-definitely-not-installed-xyz", ...])
  → THREW: Executable not found in $PATH

So the original 🔴 was a real hole, not a theoretical one, and it is now closed.

4. The changedNodes tests genuinely exercise flattening — confirmed, and this is the important one.

The author flagged the exact trap ("built through toSnapshotNode rather than the node() helper, which would not exercise flattening at all"). I tested that claim two ways rather than accepting it:

  • Disabling only the PERSISTENCE_KEYS deletion → 2 of 3 fail (_schema_version-only bump, plus the pre-existing count test). Matches the author's stated 2-of-3 exactly.
  • Disabling only the flattening (forcing isWrapper = false, leaving PERSISTENCE_KEYS intact) → 2 of the 3 new changedNodes tests fail, plus the collision test and the 4 original flattening tests (7 total).

That second run is the decisive one: if the tests were built through the node() helper they would be blind to flattening and would still pass. They fail. The tests are not vacuous — they exercise both the flattening and the persistence filter, independently. This is the trap the author called out, and the code avoids it.

5. The threshold is now genuinely pinned — confirmed in both directions.
Mutation-tested MIN_DISTINCT_TOOLS_FOR_REAL_PASS:

constant = 2 → (fail) flags a full pass one below the threshold
constant = 4 → (fail) accepts a full pass at exactly the threshold

The prior review's objection was that the constant could be changed to 4 with every test still passing. It now cannot be changed in either direction without breaking a test. This is a correct fix to a real gap in the suite.

6. _limit removal leaves no stale caller — confirmed.

grep -rn "retrievableSkillCount\|_limit\b" scripts/
  preflight.ts:299  function retrievableSkillCount(env: EvalEnv): number
  preflight.ts:387  probe = (e) => retrievableSkillCount(e),

One definition, one call site, both updated. No stale argument anywhere.

7. awaitSkillIndex's expected parameter still does what its doc says — confirmed.
This deserved a check because expected was previously passed into retrievableSkillCount and now is not. The doc comment justifies expected being declared before probe on the grounds that "probe's own default reads this parameter". After dropping _limit, probe's default no longer references expected — so that specific justification is now stale. But expected itself is entirely intact and load-bearing: it is still the comparison target in count >= expected (three sites) and in both the progress and timeout messages. The parameter does what it advertises; only the ordering rationale in the comment is now describing a dependency that no longer exists. Minor — see 🟢 below.


Requirements Check against #2263

Unchanged from the prior review; fee42ac4 adds no scope and removes none. Restated for completeness:

Acceptance criterion Status
Property matching unwraps the type key before comparison ✅
_schema_version excluded from populatedCount ✅
Regression test: nested write satisfies minProperties: 2 and a keyed lookup ✅ verified failing without the fix
Preflight probe asserts embedding presence, not row existence ✅
Test covering the cold-index case ✅ both directions
Scenarios whose setup did not verify are excluded, not scored ✅
NS_SKILL_INDEX_PROBE_DB stopgap removed ✅ N/A — never on main
#2239 arms re-run after the fix ⏳ follow-up, correctly out of scope
Pre-fix scores annotated as unreliable ⏳ follow-up, correctly out of scope

fee42ac4 additionally strengthens the verification of two ACs (the comparator behind expectNoWrites, and the uniformity threshold) that were previously satisfied in code but under-pinned by tests.


Findings

🔴 Critical

None. The prior 🔴 is correctly and completely fixed.

🟡 Improvements

None new. The five addressed 🟡 items each landed correctly — I checked each rather than assuming:

  • 📁 graph.ts:184 — JSDoc /** Narrow one CLI node object into a SnapshotNode... */ is back directly above toSnapshotNode, and the PERSISTENCE_KEYS block now carries only its own comment. The double-doc-comment is gone.
  • 📁 graph.ts:364-375 — the changedNodes behavioural change is documented on stableStringify, including the measured before/after ("1 changed node before, 0 after") and, importantly, the explicit statement that the loosening is bounded to PERSISTENCE_KEYS. That bound is what the second test enforces.
  • 📁 graph.ts:167-171 — collision precedence stated and pinned. The comment correctly frames it as "stated rather than defended" since no daemon serialization produces it.
  • 📁 preflight.ts:299 — _limit dropped cleanly.
  • 📁 runner.test.ts:820-826 — boundary tests, mutation-verified above.

🟢 Nitpicks

Nit: 📁 scripts/eval/preflight.ts:339-344 — the bare catch also swallows programming errors in a caller-supplied probe.

I verified this directly:

embeddedSkillCount("/db", () => { (undefined).x }) → 0

A TypeError inside an injected probe now silently reports "index not ready" rather than surfacing. In practice this is a good trade and I would not block on it:

  • The only production probe is the default closure, whose sole realistic throw is the missing-binary case.
  • The failure mode is fail-closed: the gate waits, then raises a proper EnvironmentError naming the skill-index problem. It degrades to a slightly-misattributed but still actionable message, never to a silent pass.
  • Narrowing the catch (e.g. matching on the message) would couple the harness to Bun's error text, which is worse.

Worth at most one clause in the existing comment acknowledging that any probe throw — not only a missing binary — maps to 0. Take or leave.

Nit: 📁 scripts/eval/preflight.ts:373-380 — expected's ordering rationale is now stale.

The comment explains that expected is declared before probe because "probe's own default reads this parameter, and TypeScript default-value closures may reference any earlier parameter". After the _limit removal, probe's default is (e) => retrievableSkillCount(e) and no longer reads expected at all. The ordering is still fine (and still the safer choice if a future probe wants expected back), but the stated reason no longer describes the code.

Principle — comments must describe the code as it is, not as it was. This is precisely the class of drift the prior review flagged at graph.ts:124; the same care applied there applies here. Two-line fix, or delete the paragraph.


Assessment of the four skips

All four justifications are sound, and I want to record why rather than just concurring:

  • Number.parseInt(...) || 0 — Correct to skip. COUNT() on SQLite cannot emit "-3" or "1e3", and every input it can emit maps to the same result under both forms. Zero behavioural delta; changing it would be churn.
  • omit → delete — Correct to skip. The prior review itself called the current form "arguably clearer about intent". Deferring to the stated preference is the right call, not a dodge.
  • 12a prompt length — Correct to skip, and the reasoning is the strongest of the four: the third clause is what makes 12d winnable, which is the defect the fixture change exists to fix. Shortening it would reintroduce the bug. The original nit was explicitly framed as "worth watching as a trend", not "change this".
  • Hoisting readServedDatabasePath — Correct to skip, and I checked the load-bearing claim. retrievableSkillCount(env) is the entire body of probe's default; hoisting the path read would require either splitting the probe signature or resolving the path in awaitSkillIndex and threading it through — which does reshape the injectable seam that six tests depend on. Against a wait dominated by a 30s embedding debounce, ~40 subprocess spawns is real but immaterial. Right trade for this PR.

scripts/ outside quality:fix/quality:check — I confirmed both scripts target only packages/desktop-app, packages/skill, and Rust. The gap is real, pre-existing, and repo-wide. Declining to fix it inside a harness-bugfix PR is correct scope discipline; it warrants its own issue.


One thing worth calling out

The author's response did something unusual and valuable: it named the trap in its own work before I could check it ("built through toSnapshotNode rather than the node() helper, which would not exercise flattening at all"). That is the single most likely way these three tests could have shipped passing-but-vacuous, and flagging it explicitly is what let me verify the claim in one targeted mutation rather than discovering it by luck. The claim also turned out to be true.

Equally, the docstring correction is the right kind of fix. The original comment asserted sqlite3 was "already required by the harness's own diagnostics" — false, since the other mentions are remediation text printed for humans. The replacement states the dependency plainly and explains why the exit-code branch alone was insufficient. A future reader now gets the real constraint instead of a reassuring falsehood.


Recommendation

APPROVE — no blocking findings. Merge when ready.

The 🔴 is closed, and closed correctly: the whole probe call is wrapped rather than just the default closure, so an injected throwing probe is covered too, and — importantly — readServedDatabasePath's own fail-closed EnvironmentError is evaluated as an argument outside the try, so it still propagates rather than being flattened into a misleading "index not ready". I checked that scoping specifically, since a wider catch is exactly where a fail-closed guard elsewhere could have been silently defeated. It was not.

The five 🟡 fixes are all real fixes rather than comment-only gestures, and two of them (the changedNodes pinning and the threshold boundary) close genuine holes in the suite's ability to detect regression — verified by mutation, in both directions. The four skips are each justified on substance.

The two remaining items are a stale comment rationale and an over-broad catch that fails in the safe direction. Neither is worth another round.

Standing follow-ups, unchanged: re-run the #2239 arms and annotate the pre-fix scores (the remaining #2263 ACs), and file the scripts/-lint-coverage gap separately. The cross-model ranking on #2239 stays non-decision-grade until the first of those is done.


Verification note: all reverts performed during this review were restored; git status shows no modifications to scripts/, and bun run test:scripts returns 257 pass / 0 fail on the restored tree.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Delta reviewed: fee42ac4 only. The 🔴 is closed correctly — the whole probe call is wrapped, so an injected throwing probe is covered, while readServedDatabasePath's own fail-closed EnvironmentError is evaluated outside the try and still propagates. Verified that scoping specifically.

Independently re-verified rather than trusted: 257 pass/0 fail; throwing-probe test confirmed to FAIL against the unwrapped call; the 3 changedNodes tests confirmed NON-vacuous by disabling flattening alone (2 fail) as well as PERSISTENCE_KEYS alone (2 fail); threshold mutation-tested in BOTH directions (constant→2 and constant→4 each break a test). All 4 skips justified on substance. 2 🟢 nits remain, neither worth another round.

All verification reverts restored; git status clean on scripts/.

Comment-only. No executable line changes (verified: the diff contains zero
non-comment +/- lines), so behaviour is unchanged and the 257 tests pass
untouched.

Both findings were the same class the first review flagged at `graph.ts:124` —
a comment that survived the change it described and now misinforms.

`awaitSkillIndex`'s `expected` parameter carried a detailed justification for
being declared BEFORE `probe`: that `probe`'s default read it, making a later
declaration a forward reference. Dropping the dead `_limit` argument in the
previous commit removed that dependency — the default is now
`(e) => retrievableSkillCount(e)`, which counts embedded rows and needs no
expected value. The comment now says why the order is kept (published
signature, positional callers) and states plainly that the hazard is gone,
rather than describing a coupling that no longer exists.

The bare `catch` added in the previous commit had no recorded rationale. The
re-review judged it a good trade but that reasoning lived only in the review
thread, so the next reader would have had to re-derive it — or "fix" it by
narrowing on Bun's error text, which is the thing worth avoiding. Now stated:
it deliberately also swallows a programming error in a caller-supplied probe,
because the alternative couples this gate to a runtime's error message, and
failing closed is safe in either case. Also records that
`readServedDatabasePath` is evaluated by the caller OUTSIDE the try, so its own
fail-closed EnvironmentError still propagates — the property that keeps the
wider catch from defeating the guard.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1ztc8m23p4WHoSToNfm89
@malibio

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed — ea260773

Both 🟢 nits addressed. Comment-only — zero non-comment lines changed (verified against the diff). 257 pass, 0 fail, unchanged.

preflight.ts:373-380 — stale ordering rationale

Correct catch, and the same drift class you flagged at graph.ts:124 in the first review. expected carried a detailed justification for being declared before probe — that probe's default read it, making a later declaration a forward reference. Dropping _limit in fee42ac4 removed exactly that dependency.

Rewritten to say why the order is kept (published signature, positional callers) and to state plainly that the hazard is gone, rather than describing a coupling that no longer exists.

preflight.ts:339-344 — the bare catch

You judged this a good trade, but that reasoning lived only in the review thread. Recorded it in the code, because the next reader would otherwise have to re-derive it — or "fix" it by narrowing on Bun's error text, which is the outcome worth preventing.

The comment now states that it deliberately swallows a programming error in a caller-supplied probe, why (narrowing would couple this gate to a runtime's error message), and that failing closed is safe either way. It also records the property you specifically checked: readServedDatabasePath is evaluated by the caller outside the try, so its own fail-closed EnvironmentError still propagates rather than being flattened into a misleading "index not ready". That is what keeps the wider catch from defeating the guard, and it was previously implicit.

Follow-ups (not this PR)

Unchanged and acknowledged: re-run the #2239 arms, annotate pre-fix scores as unreliable, and file the scripts/ lint-coverage gap separately.

Pre-push gate passed in full.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Matrix eval harness: nested properties never match, and the preflight gate can never pass

1 participant