@polycode-projects/the-mechanical-code-talker 5.0.31 → 5.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -215,6 +215,10 @@ export function createNewsSession({
215
215
  async function runPollCycle() {
216
216
  phase = "polling";
217
217
  const result = await pollNewsSources(ctx());
218
+ // The cycle's ingest writes through core appendFact directly, never the
219
+ // wrapping store, so the fold cache must drop here by hand.
220
+ foldedRows = null;
221
+ cache.rows = null;
218
222
  if (metrics.timeToFirstCompletePollMs === null) metrics.timeToFirstCompletePollMs = resolveNowMs() - bootMs;
219
223
  phase = "grounding";
220
224
  await noteFirstArticle();
@@ -224,6 +228,8 @@ export function createNewsSession({
224
228
  async function runEnrichCycle() {
225
229
  phase = "enriching";
226
230
  const result = await enrichTopTerms(ctx());
231
+ foldedRows = null;
232
+ cache.rows = null;
227
233
  phase = "idle";
228
234
  armTimer();
229
235
  return result;
@@ -298,6 +304,19 @@ export function createNewsSession({
298
304
  return { ok: true, id, format: result.format };
299
305
  },
300
306
 
307
+ /** The sources panel's checkbox path: replaces the enabled contemporary
308
+ * and kb id sets in one call. `config` is only ever handed out as a
309
+ * copy, so a real setter is the one way a toggle can narrow what the
310
+ * next poll fetches. */
311
+ setSources(ids) {
312
+ const normalized = normalizeNewsSourceIds(ids);
313
+ const kindOf = new Map(newsSourceRecords().map((r) => [r.id, r.kind]));
314
+ config.sources = normalized.filter((id) => kindOf.get(id) !== "kb");
315
+ config.kbSources = normalized.filter((id) => kindOf.get(id) === "kb");
316
+ rebuildFetchers();
317
+ return { sources: [...config.sources], kbSources: [...config.kbSources] };
318
+ },
319
+
301
320
  /** Re-arms the poll timer at `minutes`, clamped to the same floor the
302
321
  * service config enforces (0 disarms). */
303
322
  setInterval(minutes) {
@@ -311,8 +330,9 @@ export function createNewsSession({
311
330
  async ingestText(text, { fileLabel = "free-text" } = {}) {
312
331
  const nowVal = typeof now === "function" ? now() : now;
313
332
  const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
314
- const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
333
+ const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal });
315
334
  cache.rows = null;
335
+ foldedRows = null;
316
336
  return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
317
337
  },
318
338
 
@@ -343,7 +363,8 @@ export function createNewsSession({
343
363
  }
344
364
  const downgraded = ingestUploadedFactRows(rows, { fileLabel: name || "upload", now: nowVal })
345
365
  .filter((r) => r.subject && r.predicate && r.object);
346
- if (downgraded.length) { await appendFacts(memoryDir, downgraded); cache.rows = null; }
366
+ if (downgraded.length) { await appendFacts(memoryDir, downgraded); cache.rows = null;
367
+ foldedRows = null; }
347
368
  return { facts: downgraded.length, vocabAdded: 0, error: null };
348
369
  },
349
370
 
@@ -359,7 +380,7 @@ export function createNewsSession({
359
380
  for (const snapshot of items) {
360
381
  const text = [snapshot.title, snapshot.summary].filter(Boolean).join(". ");
361
382
  const sourceTag = `news-fixture:${sourceId}@${snapshot.id}`;
362
- const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
383
+ const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal });
363
384
  const allFacts = [...result.extracted, ...result.optimistic];
364
385
  snapshot.factIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
365
386
  factsTotal += allFacts.length;
@@ -371,6 +392,7 @@ export function createNewsSession({
371
392
  state.ledger = ledgerPayload(ledger);
372
393
  }
373
394
  if (factsTotal) cache.rows = null;
395
+ foldedRows = null;
374
396
  const existingIds = new Set(state.items.map((s) => s.id));
375
397
  state.items = [...state.items, ...items.filter((s) => !existingIds.has(s.id))];
376
398
  await noteFirstArticle();
@@ -0,0 +1,196 @@
1
+ # agentbench — the tmct AGENTIC measurement harness
2
+
3
+ The **sibling of chatbench**, on a new axis. chatbench measures the *chat turn*
4
+ (a request → the right grounded answer) on the CEFR ladder; AGENTBENCH measures
5
+ the **tool loop** (a request → the right *tool call(s)*) on the **TOOL-0→TOOL-9 tool-use
6
+ rungs**. Same versioned-naming + regression discipline (`BENCHMARK_AGENT_<version>.md`,
7
+ `_00N` for re-runs), one decisive difference:
8
+
9
+ > **A hallucinated tool call is an AUTOMATIC FAIL.** Emitting a call to a tool
10
+ > that is not in the declared set, or with arguments that cannot bind, fails the
11
+ > case outright — no matter how good the rest of the loop looks. This is the one
12
+ > thing a deterministic router must never do, so it is the gate the whole bench
13
+ > is built around.
14
+
15
+ **No LLM, no judge.** chatbench has a tier-2 LLM judge; AGENTBENCH has none.
16
+ Grading is **entirely deterministic** — compare the produced call(s) to the
17
+ expected call(s), gate against the capability registry, check termination and
18
+ (when required) the proof chain. A deterministic router is measured by a
19
+ deterministic ruler.
20
+
21
+ ## The pluggable "agent under test" (the seam)
22
+
23
+ The agent is a **function**, swapped without touching the harness:
24
+
25
+ ```
26
+ driver(request, tools, ctx) => Promise<loopResult>
27
+ request : string — the user's imperative
28
+ tools : string[] — the DECLARED toolset for this case
29
+ ctx : { dispatch(name,input) => {ok,text|error}, capabilityByName, config }
30
+ loopResult = { calls: [{name, input}], refused, terminated, proof, driver }
31
+ ```
32
+
33
+ Today the default is **`driver-stub.mjs`** — a trivial keyword→tool stub that
34
+ maps the obvious single-tool requests, binds one entity, executes tmct's real
35
+ `dispatchTool`, and **refuses otherwise**. It exists so the harness is runnable
36
+ and testable *now*, before Stage 1 (the resolver) and the HTTP shim exist. The
37
+ coordinator swaps in the real resolver/planner/shim driver later behind this
38
+ exact signature (`runAgentbench(cases, { driver })`).
39
+
40
+ > **Stub-driver FLOOR, not the router baseline.** Every row the stub produces is
41
+ > stamped `driver: "stub-floor"` and the runner prints a banner saying so. The
42
+ > real engine, built later, must not be compared against this mislabeled anchor:
43
+ > the stub is a floor (what a dumb keyword matcher gets), not the router's score.
44
+
45
+ ## The rungs (the TOOL ladder — tool-use capability, this bench's own scale)
46
+
47
+ | Rung | Name | What it demands |
48
+ | ---- | ---- | --------------- |
49
+ | **TOOL-0** | Direct dispatch | one obvious tool, arguments on a plate |
50
+ | **TOOL-1** | Tool selection | pick the right tool from a small declared set + bind one entity |
51
+ | **TOOL-2** | Scope refusal | **honest refuse** when no declared tool fits or the entity does not resolve |
52
+ | **TOOL-3** | Sequential composition | a bounded multi-step recipe — thread one result into the next call |
53
+ | **TOOL-4** | Conditional dispatch | conditional / retry — monitor an outcome, re-plan |
54
+ | **TOOL-5** | Goal planning | compose a plan for a novel goal (closed-world) |
55
+ | **TOOL-6** | Goal deduction | self-directed — deduce the goal, then plan (closed-world) |
56
+ | **TOOL-7** | Recovery & replanning | a step fails (empty/error) and the driver observes it and replans a fallback — `expect.recover` |
57
+ | **TOOL-8** | Composition under ambiguity | enumerate the tied readings (`expect.candidateResults`) or refuse-with-a-nudge — never an arbitrary pick |
58
+ | **TOOL-9** | Goal recognition | infer the goal from an OBSERVED trace and confirm it against a bounded scheme — N declared goals plus an explicit reject class — rather than force-fit a partial trace to the nearest goal (`expect.inferredGoal` / `expect.reject` / `expect.ambiguousGoals`) |
59
+
60
+ The stub driver is exercised only on **TOOL-0/TOOL-1/TOOL-2**; the goal driver clears the whole
61
+ ladder, **TOOL-0 through TOOL-9** (`test-benchmarks/agentbench/envelope.json`'s `rungReached`). TOOL-7's replanning
62
+ branch lives in the planner's own method table (`src/domain/router/planner.mjs`'s `recover`
63
+ method); TOOL-8's tied-candidate composer lives at the resolver's binding seam
64
+ (`src/domain/router/resolver.mjs`'s `resolveOne`) — see `PLAN_TOOL_LADDER_UPLIFT.md` for both.
65
+ TOOL-9's recognizer lives at `src/domain/router/recognize.mjs`'s `recognizeGoal` (containment over
66
+ declared operator sequences, never a score).
67
+
68
+ ## The grade (deterministic) + the metric PAIR
69
+
70
+ A case PASSES iff **all** hold:
71
+
72
+ 1. **Zero hallucinated calls** — every produced call names a tool in the declared
73
+ set *and* a real registry capability, with only accepted arg-keys and every
74
+ required arg bound. Any violation = automatic fail. (Closed-world default-deny:
75
+ see below.)
76
+ 2. **The loop terminated** (`expect.terminates`).
77
+ 3. **Outcome matches** — the produced call sequence matches `expect.calls`
78
+ (name + pinned input, positionally); OR, for an `expect.refuse` case, the
79
+ driver **refused cleanly** (no call). *Refusing-when-unsure is a PASS at the
80
+ honest-miss level.*
81
+ 4. **Proof chain** — when `expect.proof`, a non-empty proof chain whose
82
+ precondition steps are all `ok` (the glass-box receipt: which preconditions
83
+ held, which effect the call achieves).
84
+
85
+ Per rung the runner reports a **METRIC PAIR**, because a single number is
86
+ gameable — a driver that *refuses everything* scores 0% hallucination at ~0%
87
+ completion:
88
+
89
+ - **completion (coverage)** — fraction of cases whose expected outcome was
90
+ correctly produced (the right call(s), or a correct refusal);
91
+ - **hallucination rate** — fraction of cases with any out-of-set / unbindable call.
92
+
93
+ The honest **gate** is therefore **"0% hallucination AT ≥50% completion"**
94
+ (`COMPLETION_FLOOR = 0.5`). A refuse-everything driver fails the gate on
95
+ completion; a reckless driver fails it on hallucination. Only a driver that is
96
+ both **safe and useful** clears it. `--ladder` runs rungs ascending and the
97
+ first rung that fails the gate gates every rung above it (skipped with a
98
+ receipt, e.g. `rung TOOL-5 skipped: gated by TOOL-2 completion 40% < 50%`), exactly like
99
+ chatbench's grade ladder.
100
+
101
+ ## Closed-world / default-deny
102
+
103
+ The capability registry (`src/domain/router/registry.mjs`) is a deliberate, documented
104
+ **strict subset** of the `dispatchTool` switch. The model is **closed-world
105
+ default-deny**: a tool name that is not a registered capability is treated as
106
+ UNKNOWN and rejected as a hallucination (`unknown-tool`). So a planner or shim
107
+ that emits an **unregistered** tool is an automatic fail — identical to inventing
108
+ a tool that does not exist. The unbounded-output tools (`tmct_snippet`,
109
+ `tmct_context`, `tmct_context_more`) are **intentionally unregistered** (they
110
+ emit raw snippets / whole edit bundles — the most hallucination-prone surface;
111
+ they need output-size / file-read preconditions we have not committed to), and
112
+ the exclusion is recorded in `EXCLUDED_FROM_REGISTRY` so it reads as a decision,
113
+ not an omission. A conformance test (`test/bench/agentbench.test.mjs`) makes the
114
+ "verified against the switch" claim executable: every registry arg-key is proven
115
+ to be the key `dispatchTool` actually reads, and the registry is proven a strict
116
+ subset of the dispatch case set — so arg-key drift fails at merge, not at runtime.
117
+
118
+ ## Files
119
+
120
+ | file | role |
121
+ | ---- | ---- |
122
+ | `cases.jsonl` | the seed case set (TOOL-0/TOOL-1/TOOL-2 over the graph-query toolset) — append-only once the AGENTBENCH arc starts |
123
+ | `grade.mjs` | the deterministic grading core: rungs, case lint, the zero-hallucination gate, the metric pair + ladder rollup (pure, no I/O) |
124
+ | `driver-stub.mjs` | the default pluggable driver — the **stub-driver floor** |
125
+ | `run.mjs` | the deterministic runner: replays cases through the driver, writes `results/raw/run-<stamp>/product.jsonl` |
126
+ | `results/` | run output (`results/raw/` is transient) |
127
+
128
+ ## Running
129
+
130
+ ```sh
131
+ node test-benchmarks/agentbench/run.mjs # stamp defaults to the version 0.8.0
132
+ node test-benchmarks/agentbench/run.mjs --stamp 0.8.0 --ladder
133
+ node test-benchmarks/agentbench/run.mjs --rung TOOL-1 # one rung only
134
+ node test-benchmarks/agentbench/run.mjs --only ab-a0-describe-widget
135
+ # (npm run agentbench:run -- --stamp 0.8.0 is the provisioned script)
136
+ ```
137
+
138
+ - **Determinism:** no `Date.now()` in recorded output — the run stamp comes from
139
+ `--stamp` (default the pinned bench version **`0.8.0`**, stamped explicitly and
140
+ NOT read from `package.json`). Two runs over the same tree + stamp produce
141
+ byte-identical `product.jsonl`.
142
+ - **`--stamp`** must be a filesystem-safe label; **`--out`** overrides the output
143
+ dir; **`--rung <TOOL-0|…|TOOL-9>`** and **`--only <id,…>`** narrow the selection;
144
+ **`--ladder`** gates ascending rungs.
145
+
146
+ ## Case shape (`cases.jsonl`, one JSON object per line)
147
+
148
+ ```json
149
+ { "id": "ab-a1-callers-fnalpha", "rung": "TOOL-1",
150
+ "request": "which functions call fnAlpha",
151
+ "tools": ["tmct_describe", "tmct_callers", "tmct_callees"],
152
+ "expect": { "calls": [{ "name": "tmct_callers", "input": { "symbol": "fnAlpha" } }],
153
+ "terminates": true, "proof": true } }
154
+ ```
155
+
156
+ - **`rung`** — one of `TOOL-0 TOOL-1 TOOL-2 TOOL-3 TOOL-4 TOOL-5 TOOL-6 TOOL-7 TOOL-8 TOOL-9`.
157
+ - **`request`** — the imperative handed to the driver.
158
+ - **`tools`** — the DECLARED toolset (every name must be a registered capability).
159
+ - **`expect.calls`** — the expected call sequence (name + pinned input as a lower
160
+ bound; extra optional keys on the produced call are allowed). Omitted for a
161
+ refuse or a recognition case.
162
+ - **`expect.refuse`** — `true` when the correct outcome is an honest refusal
163
+ (no fitting declared tool, an unresolvable entity, or the TOOL-9 reject/ambiguous
164
+ shapes below). Mutually exclusive with `expect.calls`.
165
+ - **`expect.terminates`** — the loop must end (always `true` for these bounded cases).
166
+ - **`expect.proof`** — when `true`, a valid proof chain is required.
167
+ - **`trace`** — a TOOL-9 case only: the OBSERVED call sequence (`[{name, input}]`)
168
+ the recognizer reads back, in place of a request the driver routes.
169
+ - **`expect.inferredGoal`** — a TOOL-9 case only: the goal id the trace fits.
170
+ Mutually exclusive with `expect.refuse`.
171
+ - **`expect.reject`** — a TOOL-9 refuse case only: `true` pins the reject class
172
+ (the trace fits no declared goal).
173
+ - **`expect.ambiguousGoals`** — a TOOL-9 refuse case only: the two-or-more tied
174
+ goal ids the trace fits, when the recognizer refuses-and-lists rather than
175
+ rejecting.
176
+
177
+ ## Reference bands (ILLUSTRATIVE anchors — NOT run here)
178
+
179
+ AGENTBENCH's ladder is read against **comparable models** as illustrative
180
+ anchors, the way chatbench frames CEFR bands. These are the intended reference
181
+ points for a future write-up; **none are run by this harness** (no network, no
182
+ LLM), and no scores are claimed for them here:
183
+
184
+ | band | anchor | rough expected reach on the declarable graph-query slice |
185
+ | ---- | ------ | -------------------------------------------------------- |
186
+ | tiny-local | a small local model (≈1–3B) | TOOL-0, shaky on TOOL-1 tool selection |
187
+ | 8B-open | an 8B open-weights model | TOOL-0–TOOL-1, unreliable TOOL-2 refusal (over-eager to call) |
188
+ | Nova-micro | Amazon Nova Micro | TOOL-1–TOOL-2 |
189
+ | Nova-lite | Amazon Nova Lite | TOOL-2, some TOOL-3 |
190
+ | Haiku | Claude Haiku | TOOL-3–TOOL-4 |
191
+
192
+ The point of the bench is to say, honestly and measurably, where a
193
+ **tmct-backed** driver sits against these anchors on the slice it *declares* — and
194
+ where it should refuse. Per Phase A's `bedrock-meter` framing, the rung
195
+ AGENTBENCH proves in-envelope is exactly the request class an optimiser may route
196
+ to the deterministic $0 floor instead of a metered model.
@@ -0,0 +1,13 @@
1
+ // The runtime-readable AGENTBENCH capability envelope: package.json's
2
+ // "./envelope" export subpath resolves here, so a downstream calibration reads
3
+ // tmct's measured capability at runtime instead of hand-copying a snapshot of
4
+ // it into its own source (see generate-envelope.mjs for what the fields mean
5
+ // and how envelope.json is produced). The import below targets the sibling
6
+ // file directly, so there is no separate copy that could drift from it.
7
+ import envelope from "./envelope.json" with { type: "json" };
8
+
9
+ /** The AGENTBENCH capability envelope, freshly cloned so a caller mutating its
10
+ * result can't corrupt what the next caller sees. */
11
+ export function agentbenchEnvelope() {
12
+ return structuredClone(envelope);
13
+ }
@@ -0,0 +1,120 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "generatedFrom": {
4
+ "drivers": [
5
+ "goal-0.8.1",
6
+ "recognize-0.1.0",
7
+ "resolver-0.8.0"
8
+ ],
9
+ "stamp": "5.0.22",
10
+ "caseCount": 73
11
+ },
12
+ "ladder": {
13
+ "rungs": [
14
+ "TOOL-0",
15
+ "TOOL-1",
16
+ "TOOL-2",
17
+ "TOOL-3",
18
+ "TOOL-4",
19
+ "TOOL-5",
20
+ "TOOL-6",
21
+ "TOOL-7",
22
+ "TOOL-8",
23
+ "TOOL-9"
24
+ ],
25
+ "rungReached": "TOOL-9",
26
+ "gatedAt": null
27
+ },
28
+ "capability": {
29
+ "maxContextTokens": null,
30
+ "maxContextTokensMeasured": false,
31
+ "structuredOk": true,
32
+ "toolsOk": true
33
+ },
34
+ "metrics": {
35
+ "overall": {
36
+ "planCompletion": 1,
37
+ "resultCompletion": 1,
38
+ "hallucinationRate": 0,
39
+ "gatePass": true
40
+ },
41
+ "byRung": {
42
+ "TOOL-0": {
43
+ "n": 8,
44
+ "planCompletion": 1,
45
+ "resultCompletion": 1,
46
+ "hallucinationRate": 0,
47
+ "gatePass": true
48
+ },
49
+ "TOOL-1": {
50
+ "n": 14,
51
+ "planCompletion": 1,
52
+ "resultCompletion": 1,
53
+ "hallucinationRate": 0,
54
+ "gatePass": true
55
+ },
56
+ "TOOL-2": {
57
+ "n": 7,
58
+ "planCompletion": 1,
59
+ "resultCompletion": 1,
60
+ "hallucinationRate": 0,
61
+ "gatePass": true
62
+ },
63
+ "TOOL-3": {
64
+ "n": 6,
65
+ "planCompletion": 1,
66
+ "resultCompletion": 1,
67
+ "hallucinationRate": 0,
68
+ "gatePass": true
69
+ },
70
+ "TOOL-4": {
71
+ "n": 7,
72
+ "planCompletion": 1,
73
+ "resultCompletion": 1,
74
+ "hallucinationRate": 0,
75
+ "gatePass": true
76
+ },
77
+ "TOOL-5": {
78
+ "n": 9,
79
+ "planCompletion": 1,
80
+ "resultCompletion": 1,
81
+ "hallucinationRate": 0,
82
+ "gatePass": true
83
+ },
84
+ "TOOL-6": {
85
+ "n": 11,
86
+ "planCompletion": 1,
87
+ "resultCompletion": 1,
88
+ "hallucinationRate": 0,
89
+ "gatePass": true
90
+ },
91
+ "TOOL-7": {
92
+ "n": 3,
93
+ "planCompletion": 1,
94
+ "resultCompletion": 1,
95
+ "hallucinationRate": 0,
96
+ "gatePass": true
97
+ },
98
+ "TOOL-8": {
99
+ "n": 3,
100
+ "planCompletion": 1,
101
+ "resultCompletion": 1,
102
+ "hallucinationRate": 0,
103
+ "gatePass": true
104
+ },
105
+ "TOOL-9": {
106
+ "n": 5,
107
+ "planCompletion": 1,
108
+ "resultCompletion": 1,
109
+ "hallucinationRate": 0,
110
+ "gatePass": true
111
+ }
112
+ }
113
+ },
114
+ "notes": [
115
+ "rungReached is the highest TOOL-0..TOOL-8 rung with an unbroken gate-PASS chain from TOOL-0 (0% hallucination AT >=50% completion, agentbench/grade.mjs COMPLETION_FLOOR) — see agentbench/grade.mjs ladderGate()/highestGatePassRung().",
116
+ "toolsOk is false iff any produced call across the run named an undeclared or unknown-registry tool (the 'declared tools only, refuse otherwise' invariant). structuredOk is false iff any produced call had an unknown or missing argument against its declared schema. Both derive from src/domain/router/call-validator.mjs's hallucination taxonomy, not a hand-set guess.",
117
+ "maxContextTokens is not measured by AGENTBENCH today; it is intentionally left null rather than copying a downstream calibration's hand-set figure (that copy is exactly the drift this envelope exists to prevent).",
118
+ "Regenerate with `node agentbench/generate-envelope.mjs` after any AGENTBENCH-affecting change; the output is deterministic (no Date.now) so a clean re-run over an unchanged tree is byte-identical."
119
+ ]
120
+ }