Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(dgm): score metadata completeness for fleet promotion (#168)

Rach Pradhan37339c8f345d
diff --git a/docs/hyperagents.md b/docs/hyperagents.md
index c503d0b1..e1a9bfe5 100644
--- a/docs/hyperagents.md
+++ b/docs/hyperagents.md
@@ -218,12 +218,15 @@ through it. So Step 0 authenticates the channel; it's the precondition for
**What's signed.** Each score record carries `sig = HMAC-SHA256(key, msg)`
where `msg` is the canonical, version-tagged, newline-joined tuple
-`v1\n{prompt_sha}\n{parent_sha}\n{score:.6f}\n{run_id}\n{judge_id}\n{artifact_sha}\n{eval_set_hash}`
+`v2\n{prompt_sha}\n{parent_sha}\n{score:.6f}\n{run_id}\n{judge_id}\n{artifact_sha}\n{eval_set_hash}\n{niche}\n{provider_class}`
(score fixed to 6 decimals so Zig/Python/JS agree byte-for-byte —
-`src/main.zig scoreSigMessage`, `harness_sdk.score_signature`, the worker's
+`src/scoring.zig scoreSigMessage`, `harness_sdk.score_signature`, the worker's
`scoreSignature`). Records gain `run_id` (per-session), `judge_id`,
`artifact_sha`, `eval_set_hash` so the evaluator, the artifact it judged,
-and the held-out eval are all bound into the signature.
+and the held-out eval are all bound into the signature; v2 (issue #168 Gap 2)
+additionally binds `niche` and `provider_class` so a score can't be replayed
+into another MAP-Elites cell. Verifiers still accept the legacy `v1` envelope
+(the same tuple without the last two fields) during the transition window.
**Key custody.** `GRAFF_SCORE_KEY_FILE` names a key file *outside* cwd. The
env var holds only the path; the file is unreadable by the evolving
diff --git a/sdk/generate.py b/sdk/generate.py
index 567ba1a0..1b883d4d 100644
--- a/sdk/generate.py
+++ b/sdk/generate.py
@@ -375,9 +375,15 @@ export class Harness {{
* children with. Pass `niche` (reviewer/researcher/implementer/skeptic, or
* a custom agent) to file the score into that MAP-Elites cell so the fleet
* can promote a champion for the role; with the full persona text the genome
- * also rides over on a `fleet:propose`. Call between turns; resolves on the
+ * also rides over on a `fleet:propose`. Scale: the canonical wire scale is
+ * [0, 1]. Pass scale "unit" to assert `value` is already in [0, 1]
+ * (anything else is rejected), or "percent" to always send value/100
+ * (accepts [0, 100] — a percent-scale 0.5 means 0.005, not 0.5). Without
+ * `scale` the harness heuristic applies: [0, 1] passes as-is, values in
+ * (1, 100] are treated as percentages and normalized to /100, and values
+ * outside [0, 100] are rejected. Call between turns; resolves on the
* harness's ack. */
- async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string): Promise<void> {{
+ async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string, scale?: "unit" | "percent"): Promise<void> {{
const sha = /^[0-9a-f]{{16}}$/.test(promptOrSha) ? promptOrSha : promptFingerprint(promptOrSha);
const parent_sha = parent === undefined ? undefined
: /^[0-9a-f]{{16}}$/.test(parent) ? parent : promptFingerprint(parent);
@@ -386,7 +392,7 @@ export class Harness {{
// register it first on a `fleet:propose` (deduped by prompt_sha on the
// collector). This is the SDK analog of the harness eval loop's propose.
if (niche && !/^[0-9a-f]{{16}}$/.test(promptOrSha)) fleetSignal("propose", {{ niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha }});
- this.proc.stdin.write(JSON.stringify({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche }}) + "\\n");
+ this.proc.stdin.write(JSON.stringify({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }}) + "\\n");
// Same edge-version tolerance as setSystemPrompt: skip unknown events
// while waiting for the ack.
while (true) {{
@@ -690,8 +696,10 @@ export class RemoteHarness {{
appendSystemPrompt(text: string): Promise<void> {{ return this.setSystemPrompt(text, true); }}
/** Record an evaluation score in the server-side trajectory archive —
- * same semantics as the stdio SDK's `score()`. */
- async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string): Promise<void> {{
+ * same semantics as the stdio SDK's `score()`, including the optional
+ * `scale` ("unit" | "percent") override of the harness's
+ * value-normalization heuristic. */
+ async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string, scale?: "unit" | "percent"): Promise<void> {{
const sha = HEX16.test(promptOrSha) ? promptOrSha : await promptFingerprint(promptOrSha);
const parent_sha = parent === undefined ? undefined
: HEX16.test(parent) ? parent : await promptFingerprint(parent);
@@ -699,7 +707,7 @@ export class RemoteHarness {{
// champion for the role; the remote harness reads it from the request and
// tags its own score/submit. (Genome capture rides the harness process,
// which holds the persona text the remote bridge only references by sha.)
- for await (const ev of this.send({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche }})) {{
+ for await (const ev of this.send({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }})) {{
if (ev.type === "error") throw new Error(ev.message);
if (ev.type === "score") return;
}}
@@ -884,14 +892,18 @@ def prompt_fingerprint(text: str) -> str:
def score_signature(key: bytes, prompt_sha: str, parent_sha: str, score: float,
run_id: str, judge_id: str = "", artifact_sha: str = "",
- eval_set_hash: str = "") -> str:
+ eval_set_hash: str = "", niche: str = "",
+ provider_class: str = "") -> str:
"""Recompute a score record's HMAC the way the harness signs it (Step 0,
- fitness-channel integrity). The canonical message is version-tagged and
+ fitness-channel integrity). The canonical v2 message is version-tagged and
newline-joined with the score fixed to 6 decimals — byte-identical to the
- Zig signer (src/main.zig scoreSigMessage). `key` is the raw bytes of the
- GRAFF_SCORE_KEY_FILE file."""
- msg = "v1\\n{{}}\\n{{}}\\n{{:.6f}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}".format(
- prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash)
+ Zig signer (src/scoring.zig scoreSigMessage). v2 folds `niche` and
+ `provider_class` into the signed envelope so a score for one MAP-Elites
+ cell cannot be replayed into another. `score` is on the canonical [0, 1]
+ scale. `key` is the raw bytes of the GRAFF_SCORE_KEY_FILE file."""
+ msg = "v2\\n{{}}\\n{{}}\\n{{:.6f}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}".format(
+ prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha,
+ eval_set_hash, niche, provider_class)
return hmac.new(key, msg.encode(), hashlib.sha256).hexdigest()
@@ -899,7 +911,9 @@ def verify_score(key: bytes, rec: dict) -> bool:
"""True iff a kind:"score" trajectory/D1 record carries a valid signature
for `key`. Use this in an evolution driver's archive loader to reject
forged fitness rows (an attacker without the key cannot produce a matching
- sig). Records with no sig fail closed when a key is set."""
+ sig). Verifies the v2 envelope first, then falls back to legacy v1 rows
+ (signed before niche/provider_class entered the envelope — transition
+ window only). Records with no sig fail closed when a key is set."""
sig = rec.get("sig") or ""
if not sig:
return False
@@ -907,8 +921,20 @@ def verify_score(key: bytes, rec: dict) -> bool:
key, rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",
float(rec.get("score", "nan")), rec.get("run_id", ""),
rec.get("judge_id", ""), rec.get("artifact_sha", ""),
+ rec.get("eval_set_hash", ""),
+ # D1 returns NULL (None) for an empty niche/provider_class — "{{}}"
+ # would format it as the literal "None" and poison the message.
+ rec.get("niche", "") or "",
+ rec.get("provider_class", "") or "")
+ if hmac.compare_digest(sig, want):
+ return True
+ legacy = "v1\\n{{}}\\n{{}}\\n{{:.6f}}\\n{{}}\\n{{}}\\n{{}}\\n{{}}".format(
+ rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",
+ float(rec.get("score", "nan")), rec.get("run_id", ""),
+ rec.get("judge_id", ""), rec.get("artifact_sha", ""),
rec.get("eval_set_hash", ""))
- return hmac.compare_digest(sig, want)
+ return hmac.compare_digest(
+ sig, hmac.new(key, legacy.encode(), hashlib.sha256).hexdigest())
class Harness:
"""Drives a `harness --json` subprocess. One turn = send text, stream events.
@@ -1041,7 +1067,7 @@ class Harness:
def score(self, prompt_or_sha: str, value: float, notes: str = "",
parent: Optional[str] = None, judge_id: str = "",
artifact_sha: str = "", eval_set_hash: str = "",
- niche: str = "") -> None:
+ niche: str = "", scale: str = "") -> None:
"""Record an evaluation score for an agent/prompt variant in the
trajectory archive (harness.trajectory.jsonl) — the DGM evaluation
phase writing back. `prompt_or_sha` is either the full system-prompt
@@ -1057,7 +1083,15 @@ class Harness:
`niche` (reviewer/researcher/implementer/skeptic, or a custom agent)
files the score into that MAP-Elites cell so the fleet can promote a
champion for the role; with the full persona text the genome also rides
- over on a `fleet:propose`. Call between turns; blocks until the harness
+ over on a `fleet:propose`.
+
+ Scale: the canonical wire scale is [0, 1]. Pass scale="unit" to
+ assert `value` is already in [0, 1] (anything else is rejected), or
+ scale="percent" to always send value/100 (accepts [0, 100] — note a
+ percent-scale 0.5 means 0.005, not 0.5). Without `scale` the harness
+ heuristic applies: [0, 1] passes as-is, values in (1, 100] are
+ treated as percentages and normalized to /100, and values outside
+ [0, 100] are rejected. Call between turns; blocks until the harness
acks."""
assert self.proc.stdin and self.proc.stdout
sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha) \\
@@ -1074,6 +1108,8 @@ class Harness:
req["eval_set_hash"] = eval_set_hash
if niche:
req["niche"] = niche
+ if scale:
+ req["scale"] = scale
# Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha
# joins a stored genome, so when we hold the full persona text + a niche,
# register it first (deduped by prompt_sha on the collector).
@@ -1258,10 +1294,12 @@ class RemoteHarness:
def score(self, prompt_or_sha: str, value: float, notes: str = "",
parent: Optional[str] = None, judge_id: str = "",
artifact_sha: str = "", eval_set_hash: str = "",
- niche: str = "") -> None:
+ niche: str = "", scale: str = "") -> None:
"""Record an evaluation score in the server-side trajectory archive —
same semantics (and provenance fields) as `Harness.score`, including
- the `niche` MAP-Elites tag and genome-send."""
+ the `niche` MAP-Elites tag, genome-send, and the optional `scale`
+ ("unit" | "percent") override of the harness's value-normalization
+ heuristic."""
sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha) \\
else prompt_fingerprint(prompt_or_sha)
req = {{"type": "score", "prompt_sha": sha, "score": value, "notes": notes}}
@@ -1276,6 +1314,8 @@ class RemoteHarness:
req["eval_set_hash"] = eval_set_hash
if niche:
req["niche"] = niche
+ if scale:
+ req["scale"] = scale
# Genome-send (docs §9.B): register the persona when we hold the full
# text + a niche so a promoted cell has a genome to serve.
if niche and not re.fullmatch(r"[0-9a-f]{{16}}", prompt_or_sha):
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index 9ffeb142..06ddb9c6 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -146,14 +146,18 @@ def prompt_fingerprint(text: str) -> str:
def score_signature(key: bytes, prompt_sha: str, parent_sha: str, score: float,
run_id: str, judge_id: str = "", artifact_sha: str = "",
- eval_set_hash: str = "") -> str:
+ eval_set_hash: str = "", niche: str = "",
+ provider_class: str = "") -> str:
"""Recompute a score record's HMAC the way the harness signs it (Step 0,
- fitness-channel integrity). The canonical message is version-tagged and
+ fitness-channel integrity). The canonical v2 message is version-tagged and
newline-joined with the score fixed to 6 decimals — byte-identical to the
- Zig signer (src/main.zig scoreSigMessage). `key` is the raw bytes of the
- GRAFF_SCORE_KEY_FILE file."""
- msg = "v1\n{}\n{}\n{:.6f}\n{}\n{}\n{}\n{}".format(
- prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash)
+ Zig signer (src/scoring.zig scoreSigMessage). v2 folds `niche` and
+ `provider_class` into the signed envelope so a score for one MAP-Elites
+ cell cannot be replayed into another. `score` is on the canonical [0, 1]
+ scale. `key` is the raw bytes of the GRAFF_SCORE_KEY_FILE file."""
+ msg = "v2\n{}\n{}\n{:.6f}\n{}\n{}\n{}\n{}\n{}\n{}".format(
+ prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha,
+ eval_set_hash, niche, provider_class)
return hmac.new(key, msg.encode(), hashlib.sha256).hexdigest()
@@ -161,7 +165,9 @@ def verify_score(key: bytes, rec: dict) -> bool:
"""True iff a kind:"score" trajectory/D1 record carries a valid signature
for `key`. Use this in an evolution driver's archive loader to reject
forged fitness rows (an attacker without the key cannot produce a matching
- sig). Records with no sig fail closed when a key is set."""
+ sig). Verifies the v2 envelope first, then falls back to legacy v1 rows
+ (signed before niche/provider_class entered the envelope — transition
+ window only). Records with no sig fail closed when a key is set."""
sig = rec.get("sig") or ""
if not sig:
return False
@@ -169,8 +175,20 @@ def verify_score(key: bytes, rec: dict) -> bool:
key, rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",
float(rec.get("score", "nan")), rec.get("run_id", ""),
rec.get("judge_id", ""), rec.get("artifact_sha", ""),
+ rec.get("eval_set_hash", ""),
+ # D1 returns NULL (None) for an empty niche/provider_class — "{}"
+ # would format it as the literal "None" and poison the message.
+ rec.get("niche", "") or "",
+ rec.get("provider_class", "") or "")
+ if hmac.compare_digest(sig, want):
+ return True
+ legacy = "v1\n{}\n{}\n{:.6f}\n{}\n{}\n{}\n{}".format(
+ rec.get("prompt_sha", ""), rec.get("parent_sha", "") or "",
+ float(rec.get("score", "nan")), rec.get("run_id", ""),
+ rec.get("judge_id", ""), rec.get("artifact_sha", ""),
rec.get("eval_set_hash", ""))
- return hmac.compare_digest(sig, want)
+ return hmac.compare_digest(
+ sig, hmac.new(key, legacy.encode(), hashlib.sha256).hexdigest())
class Harness:
"""Drives a `harness --json` subprocess. One turn = send text, stream events.
@@ -303,7 +321,7 @@ class Harness:
def score(self, prompt_or_sha: str, value: float, notes: str = "",
parent: Optional[str] = None, judge_id: str = "",
artifact_sha: str = "", eval_set_hash: str = "",
- niche: str = "") -> None:
+ niche: str = "", scale: str = "") -> None:
"""Record an evaluation score for an agent/prompt variant in the
trajectory archive (harness.trajectory.jsonl) — the DGM evaluation
phase writing back. `prompt_or_sha` is either the full system-prompt
@@ -319,7 +337,15 @@ class Harness:
`niche` (reviewer/researcher/implementer/skeptic, or a custom agent)
files the score into that MAP-Elites cell so the fleet can promote a
champion for the role; with the full persona text the genome also rides
- over on a `fleet:propose`. Call between turns; blocks until the harness
+ over on a `fleet:propose`.
+
+ Scale: the canonical wire scale is [0, 1]. Pass scale="unit" to
+ assert `value` is already in [0, 1] (anything else is rejected), or
+ scale="percent" to always send value/100 (accepts [0, 100] — note a
+ percent-scale 0.5 means 0.005, not 0.5). Without `scale` the harness
+ heuristic applies: [0, 1] passes as-is, values in (1, 100] are
+ treated as percentages and normalized to /100, and values outside
+ [0, 100] are rejected. Call between turns; blocks until the harness
acks."""
assert self.proc.stdin and self.proc.stdout
sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha) \
@@ -336,6 +362,8 @@ class Harness:
req["eval_set_hash"] = eval_set_hash
if niche:
req["niche"] = niche
+ if scale:
+ req["scale"] = scale
# Genome-send (docs §9.B): a cell only promotes when a score's prompt_sha
# joins a stored genome, so when we hold the full persona text + a niche,
# register it first (deduped by prompt_sha on the collector).
@@ -520,10 +548,12 @@ class RemoteHarness:
def score(self, prompt_or_sha: str, value: float, notes: str = "",
parent: Optional[str] = None, judge_id: str = "",
artifact_sha: str = "", eval_set_hash: str = "",
- niche: str = "") -> None:
+ niche: str = "", scale: str = "") -> None:
"""Record an evaluation score in the server-side trajectory archive —
same semantics (and provenance fields) as `Harness.score`, including
- the `niche` MAP-Elites tag and genome-send."""
+ the `niche` MAP-Elites tag, genome-send, and the optional `scale`
+ ("unit" | "percent") override of the harness's value-normalization
+ heuristic."""
sha = prompt_or_sha if re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha) \
else prompt_fingerprint(prompt_or_sha)
req = {"type": "score", "prompt_sha": sha, "score": value, "notes": notes}
@@ -538,6 +568,8 @@ class RemoteHarness:
req["eval_set_hash"] = eval_set_hash
if niche:
req["niche"] = niche
+ if scale:
+ req["scale"] = scale
# Genome-send (docs §9.B): register the persona when we hold the full
# text + a niche so a promoted cell has a genome to serve.
if niche and not re.fullmatch(r"[0-9a-f]{16}", prompt_or_sha):
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 6e765915..5c0cfda7 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -324,9 +324,15 @@ export class Harness {
* children with. Pass `niche` (reviewer/researcher/implementer/skeptic, or
* a custom agent) to file the score into that MAP-Elites cell so the fleet
* can promote a champion for the role; with the full persona text the genome
- * also rides over on a `fleet:propose`. Call between turns; resolves on the
+ * also rides over on a `fleet:propose`. Scale: the canonical wire scale is
+ * [0, 1]. Pass scale "unit" to assert `value` is already in [0, 1]
+ * (anything else is rejected), or "percent" to always send value/100
+ * (accepts [0, 100] — a percent-scale 0.5 means 0.005, not 0.5). Without
+ * `scale` the harness heuristic applies: [0, 1] passes as-is, values in
+ * (1, 100] are treated as percentages and normalized to /100, and values
+ * outside [0, 100] are rejected. Call between turns; resolves on the
* harness's ack. */
- async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string): Promise<void> {
+ async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string, scale?: "unit" | "percent"): Promise<void> {
const sha = /^[0-9a-f]{16}$/.test(promptOrSha) ? promptOrSha : promptFingerprint(promptOrSha);
const parent_sha = parent === undefined ? undefined
: /^[0-9a-f]{16}$/.test(parent) ? parent : promptFingerprint(parent);
@@ -335,7 +341,7 @@ export class Harness {
// register it first on a `fleet:propose` (deduped by prompt_sha on the
// collector). This is the SDK analog of the harness eval loop's propose.
if (niche && !/^[0-9a-f]{16}$/.test(promptOrSha)) fleetSignal("propose", { niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha });
- this.proc.stdin.write(JSON.stringify({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche }) + "\n");
+ this.proc.stdin.write(JSON.stringify({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }) + "\n");
// Same edge-version tolerance as setSystemPrompt: skip unknown events
// while waiting for the ack.
while (true) {
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index 7b09044c..ced29c86 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -207,8 +207,10 @@ export class RemoteHarness {
appendSystemPrompt(text: string): Promise<void> { return this.setSystemPrompt(text, true); }
/** Record an evaluation score in the server-side trajectory archive —
- * same semantics as the stdio SDK's `score()`. */
- async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string): Promise<void> {
+ * same semantics as the stdio SDK's `score()`, including the optional
+ * `scale` ("unit" | "percent") override of the harness's
+ * value-normalization heuristic. */
+ async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string, scale?: "unit" | "percent"): Promise<void> {
const sha = HEX16.test(promptOrSha) ? promptOrSha : await promptFingerprint(promptOrSha);
const parent_sha = parent === undefined ? undefined
: HEX16.test(parent) ? parent : await promptFingerprint(parent);
@@ -216,7 +218,7 @@ export class RemoteHarness {
// champion for the role; the remote harness reads it from the request and
// tags its own score/submit. (Genome capture rides the harness process,
// which holds the persona text the remote bridge only references by sha.)
- for await (const ev of this.send({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche })) {
+ for await (const ev of this.send({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale })) {
if (ev.type === "error") throw new Error(ev.message);
if (ev.type === "score") return;
}
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index f1a0d162..bba19d0c 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -91,7 +91,15 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
// real eval-driven work — only darwincode/JSON-proto runs ever submitted.
if (combined) |s| {
if (improved and s > 0) { // s>0: skip the initial-state / total-failure 0 (don't pollute the cell mean)
- if (telemetry.g_telem) |t| {
+ if (s > 100) {
+ // Review F8: parseEvalScore does NOT bound its result (a stray
+ // "score: 9000" line parses as 9000) — an out-of-[0,100] score
+ // must never be signed or submitted. Skip the score AND its
+ // paired propose/submit, mirroring mainloop /score's explicit
+ // rejection, so the submit counter stays in sync with stored
+ // scores. The local eval verdict below still shows the number.
+ if (self.tracer) |tr| tr.note("fleet", "score skipped: eval score outside [0,100]");
+ } else if (telemetry.g_telem) |t| {
const sys = self.systemPrompt();
const genome_fp = promptFingerprint(sys);
const esh_fp = promptFingerprint(cmd);
@@ -102,19 +110,36 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
// --niche tags this score's cell. Without it the score lands in the
// anonymous "" niche, which pullElites can never match to a builtin —
// so an eval session that wants to grow a champion must name its role.
- const niche = self.eval_niche;
+ // Truncated to 64 chars and sanitized (tab/newline/CR → ' ', review
+ // F7) BEFORE signing (fleetEvent's own niche cap, same as mainloop
+ // /score) so signed bytes equal ingested bytes.
+ var niche_buf: [64]u8 = undefined;
+ const niche = scoring.sanitizeMetaField(&niche_buf, utf8Prefix(self.eval_niche, 64));
// Genome-send (graff-dgm.md §B): the eval genome is this agent's own
// persona, never spawned via runSub, so its prompt_text never reached
// the worker. A cell only promotes when harness_scores joins to a
// harness_genomes row, so ride the genome text over on a `propose`
// (deduped by prompt_sha) before the score — else a winning eval cell
// has nothing to serve. Gated on a niche: a "" cell is unpromotable.
- if (niche.len > 0) t.fleetEvent("propose", niche, genome, "", pclass, "", 0, sys);
- const sig = signScore(genome, "", s, run_id, "", "", esh);
+ // Oversized genomes skip the propose (review F6): the server verifies
+ // the fingerprint over the carried text, so a truncated genome would
+ // be dropped there anyway.
+ if (niche.len > 0) {
+ if (sys.len <= telemetry.Telemetry.max_propose_text)
+ t.fleetEvent("propose", niche, genome, "", pclass, "", 0, sys)
+ else if (self.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");
+ }
+ // SCORE SCALE CONTRACT (issue #168 Gap 4): local UX stays
+ // 0-100 (the /100 verdicts below, eval_best, eval_target),
+ // but every score that leaves the client is [0,1] — divide at
+ // the emission boundary; s01 is what gets signed (v2: niche +
+ // provider_class in the envelope) and sent.
+ const s01 = s / 100.0;
+ const sig = signScore(genome, "", s01, run_id, "", "", esh, niche, pclass);
const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
var provbuf: [512]u8 = undefined;
const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche }) catch "";
- t.scoreEvent(genome, "", s, run_id, sig_s, prov);
+ t.scoreEvent(genome, "", s01, run_id, sig_s, prov);
t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
}
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index c1276e15..010d0ad0 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -263,39 +263,81 @@ pub fn run(ctx: *Ctx) !void {
continue;
}
if (std.mem.eql(u8, rtype, "score")) {
+ // Fingerprint fields must be exactly 16 hex chars — a
+ // length-only check would let an embedded newline through into
+ // the signed v2 envelope (field-shift ambiguity).
+ const hex16 = struct {
+ fn ok(s: []const u8) bool {
+ if (s.len != 16) return false;
+ for (s) |c| if (!std.ascii.isHex(c)) return false;
+ return true;
+ }
+ };
const sha = if (parsed.object.get("prompt_sha")) |v| (if (v == .string) v.string else "") else "";
const sc: f64 = if (parsed.object.get("score")) |v| switch (v) {
.float => |x| x,
.integer => |x| @floatFromInt(x),
else => std.math.nan(f64),
} else std.math.nan(f64);
- if (sha.len != 16 or std.math.isNan(sc)) {
+ if (!hex16.ok(sha) or std.math.isNan(sc)) {
ctx.root.emit(.{ .type = "error", .message = "score needs prompt_sha (16 hex chars) and a numeric score" });
continue;
}
+ const reqStr = struct {
+ fn s(o: std.json.ObjectMap, k: []const u8) []const u8 {
+ return if (o.get(k)) |v| (if (v == .string) v.string else "") else "";
+ }
+ };
+ // SCORE SCALE CONTRACT (issue #168 Gap 4): the canonical wire
+ // scale is [0,1]. An explicit "scale" field overrides the
+ // heuristic (review F9): "percent" always divides by 100 and
+ // accepts values up to 100 (so a percent-scale 0.5 means
+ // 0.005, not 0.5); "unit" requires [0,1] as-is. Absent, the
+ // heuristic applies: [0,1] passes, (1,100] is read as a
+ // percentage and divides by 100, and anything else is rejected
+ // here so the backend never has to clamp a 43 into a fake 1.0.
+ const scale = reqStr.s(parsed.object, "scale");
+ // An unrecognized scale must fail loudly, not fall through to
+ // the heuristic — a typo like "Percent" silently reinterpreting
+ // 0.7-of-100 as unit-scale 0.7 is a 100x corruption.
+ if (scale.len > 0 and !std.mem.eql(u8, scale, "percent") and !std.mem.eql(u8, scale, "unit")) {
+ ctx.root.emit(.{ .type = "error", .message = "unknown scale: use \"unit\" or \"percent\" (or omit it for the [0,1]/(1,100] heuristic)" });
+ continue;
+ }
+ const normalized: ?f64 = if (std.mem.eql(u8, scale, "percent"))
+ (if (sc < 0 or sc > 100) null else sc / 100.0)
+ else if (std.mem.eql(u8, scale, "unit"))
+ (if (sc < 0 or sc > 1) null else sc)
+ else
+ scoring.normalizeOutboundScore(sc);
+ const sc01 = normalized orelse {
+ ctx.root.emit(.{ .type = "error", .message = "score out of range: scale=\"unit\" requires [0,1], scale=\"percent\" requires [0,100] (sent as value/100); without scale, [0,1] passes, (1,100] is normalized to /100, and values outside [0,100] are rejected" });
+ continue;
+ };
const notes = if (parsed.object.get("notes")) |v| (if (v == .string) v.string else "") else "";
// Optional genome lineage: which prompt this variant was
// mutated from — the children-count input for DGM parent
// selection.
- const parent = if (parsed.object.get("parent_sha")) |v| (if (v == .string and v.string.len == 16) v.string else "") else "";
+ const parent = if (parsed.object.get("parent_sha")) |v| (if (v == .string and hex16.ok(v.string)) v.string else "") else "";
// Provenance (Step 0): the driver names which judge produced
// the score, the artifact it judged, and the eval-set hash;
// run_id defaults to this session's. All are HMAC-signed so a
- // forged trajectory row is detectable.
- const reqStr = struct {
- fn s(o: std.json.ObjectMap, k: []const u8) []const u8 {
- return if (o.get(k)) |v| (if (v == .string) v.string else "") else "";
- }
- };
- const judge_id = util.utf8Prefix(reqStr.s(parsed.object, "judge_id"), 64);
- const artifact_sha = util.utf8Prefix(reqStr.s(parsed.object, "artifact_sha"), 64);
+ // forged trajectory row is detectable. User-controlled fields
+ // are sanitized (tab/newline/CR → ' ', review F7) BEFORE
+ // signing so the signed bytes equal the transported bytes —
+ // an embedded tab would otherwise split the prov transport.
+ var jid_buf: [64]u8 = undefined;
+ var art_buf: [64]u8 = undefined;
+ const judge_id = scoring.sanitizeMetaField(&jid_buf, util.utf8Prefix(reqStr.s(parsed.object, "judge_id"), 64));
+ const artifact_sha = scoring.sanitizeMetaField(&art_buf, util.utf8Prefix(reqStr.s(parsed.object, "artifact_sha"), 64));
// DGM lever: when the score omits eval_set_hash but an --eval suite is
// configured, stamp the suite's stable fingerprint so scores group into a
// promotable (niche × tier × suite) cell. Same --eval cmd → same hash
// across installs → the fleet can rank + promote a champion.
var esh_buf: [16]u8 = undefined;
+ var eshp_buf: [64]u8 = undefined;
const eval_set_hash = eshblk: {
- const provided = util.utf8Prefix(reqStr.s(parsed.object, "eval_set_hash"), 64);
+ const provided = scoring.sanitizeMetaField(&eshp_buf, util.utf8Prefix(reqStr.s(parsed.object, "eval_set_hash"), 64));
if (provided.len > 0) break :eshblk provided;
if (ctx.root.eval_cmd) |c| {
esh_buf = scoring.promptFingerprint(c);
@@ -303,31 +345,45 @@ pub fn run(ctx: *Ctx) !void {
}
break :eshblk "";
};
- const req_run = reqStr.s(parsed.object, "run_id");
- const run_id: []const u8 = if (req_run.len > 0) util.utf8Prefix(req_run, 64) else &scoring.g_run_id;
- const sig = scoring.signScore(sha, parent, sc, run_id, judge_id, artifact_sha, eval_set_hash);
+ // run_id is signed too — sanitize it like the other meta
+ // fields so an embedded newline can't shift the v2 envelope
+ // (one signature verifying two different field bindings).
+ var run_buf: [64]u8 = undefined;
+ const req_run = scoring.sanitizeMetaField(&run_buf, util.utf8Prefix(reqStr.s(parsed.object, "run_id"), 64));
+ const run_id: []const u8 = if (req_run.len > 0) req_run else &scoring.g_run_id;
+ // v2 envelope (issue #168 Gap 2): niche + provider_class are
+ // signed, so a score for one cell can't be replayed into
+ // another by mutating transport fields. The niche is truncated
+ // to 64 (fleetEvent's own cap) and sanitized BEFORE signing so
+ // the signed bytes match what the backend ingests.
+ var niche_buf: [64]u8 = undefined;
+ const req_niche = scoring.sanitizeMetaField(&niche_buf, util.utf8Prefix(reqStr.s(parsed.object, "niche"), 64));
+ const pclass = scoring.providerClass(ctx.root.provider.model);
+ const sig = scoring.signScore(sha, parent, sc01, run_id, judge_id, artifact_sha, eval_set_hash, req_niche, pclass);
const signed = scoring.g_score_key != null;
if (trace.g_traj) |tj| tj.node(.{
.kind = "score",
.prompt_sha = sha,
.parent_sha = parent,
- .score = sc,
+ .score = sc01,
.notes = util.utf8Prefix(notes, 200),
.run_id = run_id,
.judge_id = judge_id,
.artifact_sha = artifact_sha,
.eval_set_hash = eval_set_hash,
+ .niche = req_niche,
+ .provider_class = pclass,
.sig = if (signed) @as([]const u8, &sig) else "",
.t = tj.elapsedMs(),
});
var provbuf: [512]u8 = undefined;
- // prov = judge_id, artifact_sha, eval_set_hash (the signed Step-0 fields)
- // + provider_class, niche (unsigned transport) so harness_scores can form
+ // prov = judge_id, artifact_sha, eval_set_hash + provider_class, niche —
+ // all five folded into the v2 HMAC — so harness_scores can form
// (niche x provider_class x eval_set_hash) cells the fleet ranks over.
- const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ judge_id, artifact_sha, eval_set_hash, scoring.providerClass(ctx.root.provider.model), reqStr.s(parsed.object, "niche") }) catch "";
- if (telemetry.g_telem) |t| t.scoreEvent(sha, parent, sc, run_id, if (signed) @as([]const u8, &sig) else "", prov);
+ const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ judge_id, artifact_sha, eval_set_hash, pclass, req_niche }) catch "";
+ if (telemetry.g_telem) |t| t.scoreEvent(sha, parent, sc01, run_id, if (signed) @as([]const u8, &sig) else "", prov);
// fleet:submit (docs §9.B) — a scored, pinned-eval variant entered the fleet grid.
- if (eval_set_hash.len > 0) if (telemetry.g_telem) |t| t.fleetEvent("submit", reqStr.s(parsed.object, "niche"), sha, "", scoring.providerClass(ctx.root.provider.model), eval_set_hash, 0, "");
+ if (eval_set_hash.len > 0) if (telemetry.g_telem) |t| t.fleetEvent("submit", req_niche, sha, "", pclass, eval_set_hash, 0, "");
ctx.root.emit(.{ .type = "score", .ok = true, .prompt_sha = sha, .signed = signed });
continue;
}
diff --git a/src/scoring.zig b/src/scoring.zig
index 6ed0199a..a3e15ef7 100644
--- a/src/scoring.zig
+++ b/src/scoring.zig
@@ -81,7 +81,12 @@ pub var g_run_id: [16]u8 = @splat('0');
/// Canonical signing message — newline-delimited, version-prefixed, with the
/// score formatted to a fixed 6 decimals so Zig/Python/JS agree byte-for-byte.
-/// `buf` must hold the message; returns the slice written.
+/// v2 (issue #168 Gap 2) folds niche + provider_class into the envelope so a
+/// score signed for one MAP-Elites cell cannot be replayed into another by
+/// mutating what used to be unsigned transport fields. New clients emit v2
+/// only; the backend verifies v2 first and falls back to v1 for legacy rows
+/// during the transition window. `buf` must hold the message; returns the
+/// slice written.
pub fn scoreSigMessage(
buf: []u8,
prompt_sha: []const u8,
@@ -91,13 +96,17 @@ pub fn scoreSigMessage(
judge_id: []const u8,
artifact_sha: []const u8,
eval_set_hash: []const u8,
+ niche: []const u8,
+ provider_class: []const u8,
) ?[]const u8 {
- return std.fmt.bufPrint(buf, "v1\n{s}\n{s}\n{d:.6}\n{s}\n{s}\n{s}\n{s}", .{
- prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash,
+ return std.fmt.bufPrint(buf, "v2\n{s}\n{s}\n{d:.6}\n{s}\n{s}\n{s}\n{s}\n{s}\n{s}", .{
+ prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash, niche, provider_class,
}) catch null;
}
/// HMAC-SHA256 of the canonical message, hex. "" when no key is configured.
+/// SCORE SCALE CONTRACT: `score` here (and in every scoreEvent / fleet
+/// submit) is on the canonical [0,1] scale — normalize before signing.
pub fn signScore(
prompt_sha: []const u8,
parent_sha: []const u8,
@@ -106,15 +115,46 @@ pub fn signScore(
judge_id: []const u8,
artifact_sha: []const u8,
eval_set_hash: []const u8,
+ niche: []const u8,
+ provider_class: []const u8,
) [64]u8 {
const key = g_score_key orelse return @splat(0);
var msgbuf: [512]u8 = undefined;
- const msg = scoreSigMessage(&msgbuf, prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash) orelse return @splat(0);
+ const msg = scoreSigMessage(&msgbuf, prompt_sha, parent_sha, score, run_id, judge_id, artifact_sha, eval_set_hash, niche, provider_class) orelse return @splat(0);
var mac: [std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8 = undefined;
std.crypto.auth.hmac.sha2.HmacSha256.create(&mac, msg, key);
return std.fmt.bytesToHex(mac, .lower);
}
+/// SCORE SCALE CONTRACT (issue #168 Gap 4): every score that leaves the
+/// client is in [0,1]; local display/UX stays 0-100. This is the /score
+/// ingestion-boundary normalizer: [0,1] passes through, (1,100] is a
+/// percentage and divides by 100, and anything else (negative, >100, NaN)
+/// returns null so the caller rejects it — the backend rejects out-of-range
+/// scores rather than silently clamping them into a fake 1.0.
+pub fn normalizeOutboundScore(v: f64) ?f64 {
+ if (std.math.isNan(v) or v < 0 or v > 100) return null;
+ return if (v > 1) v / 100.0 else v;
+}
+
+/// Sanitize a user-controlled provenance field BEFORE signing (issue #168
+/// review F7): '\t', '\n', '\r' become ' '. The signing message is
+/// newline-delimited and scoreEvent's prov transport is tab-separated, so an
+/// embedded tab/newline in e.g. a --niche would make the signed bytes differ
+/// from the transported bytes and break verification server-side. Writes
+/// into `buf` (result is at most buf.len bytes); callers pass the same
+/// sanitized slice to both signScore and the telemetry event.
+pub fn sanitizeMetaField(buf: []u8, field: []const u8) []const u8 {
+ const n = @min(buf.len, field.len);
+ for (field[0..n], buf[0..n]) |c, *out| {
+ out.* = switch (c) {
+ '\t', '\n', '\r' => ' ',
+ else => c,
+ };
+ }
+ return buf[0..n];
+}
+
/// Read the signing key from GRAFF_SCORE_KEY_FILE (a path outside cwd) into
/// `arena`. Whitespace-trimmed; null when unset, unreadable, or empty.
pub fn loadScoreKey(io: Io, arena: Allocator, environ: anytype) ?[]const u8 {
@@ -133,20 +173,25 @@ test "promptFingerprint is stable, short, and collision-visible" {
test "score signing message is canonical and cross-language stable" {
// This exact byte layout is the contract the Python/JS verifiers
// reimplement — a change here breaks signature verification, so it is
- // pinned. Score is fixed to 6 decimals; fields newline-joined; "v1" tag.
+ // pinned. Score is fixed to 6 decimals; fields newline-joined; "v2" tag
+ // with niche + provider_class as the last two (now-signed) fields.
var buf: [512]u8 = undefined;
- const msg = scoreSigMessage(&buf, "aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "").?;
- try std.testing.expectEqualStrings("v1\naaaaaaaaaaaaaaaa\n\n0.500000\nrun123\nj1\n\n", msg);
+ const msg = scoreSigMessage(&buf, "aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "", "", "").?;
+ try std.testing.expectEqualStrings("v2\naaaaaaaaaaaaaaaa\n\n0.500000\nrun123\nj1\n\n\n\n", msg);
// With a key, signScore is a stable, key-dependent HMAC; without one
// (default global) it is all-zero hex and callers omit it.
g_score_key = "testkey";
defer g_score_key = null;
- const sig = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "");
- const sig2 = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "");
+ const sig = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "", "reviewer", "mid");
+ const sig2 = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "", "reviewer", "mid");
try std.testing.expectEqualStrings(&sig, &sig2); // deterministic
- const sig_changed = signScore("aaaaaaaaaaaaaaaa", "", 0.6, "run123", "j1", "", "");
+ const sig_changed = signScore("aaaaaaaaaaaaaaaa", "", 0.6, "run123", "j1", "", "", "reviewer", "mid");
try std.testing.expect(!std.mem.eql(u8, &sig, &sig_changed)); // score is signed
+ const sig_niche = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "", "skeptic", "mid");
+ try std.testing.expect(!std.mem.eql(u8, &sig, &sig_niche)); // niche is signed (v2)
+ const sig_tier = signScore("aaaaaaaaaaaaaaaa", "", 0.5, "run123", "j1", "", "", "reviewer", "small");
+ try std.testing.expect(!std.mem.eql(u8, &sig, &sig_tier)); // provider_class is signed (v2)
}
test "providerClass buckets models by capability tier" {
try std.testing.expectEqualStrings("frontier", providerClass("claude-opus-4-8"));
@@ -162,18 +207,21 @@ test "providerClass buckets models by capability tier" {
try std.testing.expectEqualStrings("mid", providerClass("grok-build")); // out=2 → mid
try std.testing.expectEqualStrings("small", providerClass("mimo-v2.5")); // out=0.28 → small
}
-test "signScore: matches the Python SDK HMAC for a known key" {
- // hmac.new(b"test-key", msg, sha256) over the canonical tuple above.
+test "signScore: golden v2 vector (backend + SDK must match byte-for-byte)" {
+ // hmac.new(b"test-key", msg, sha256) over the canonical v2 tuple:
+ // "v2\na1b2\nc3d4\n0.500000\nrun1\nreplay-v1\nart\nevalhash\nreviewer\nfrontier"
+ // The worker's v2 verifier and the Python SDK's score_signature are
+ // checked against this exact vector — do not regenerate it casually.
const saved = g_score_key;
defer g_score_key = saved;
g_score_key = "test-key";
- const sig = signScore("a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash");
+ const sig = signScore("a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash", "reviewer", "frontier");
try std.testing.expectEqualStrings(
- "32023137ff08de5962f81a0d0f7229bc5c0fb26b8c3399b8af54138fb47c6138",
+ "2b27be06ec7b686b67f4c1f248d96841b2db8391030030ebee958ce9c53e4d1d",
&sig,
);
g_score_key = null;
- const unsigned = signScore("a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash");
+ const unsigned = signScore("a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash", "reviewer", "frontier");
try std.testing.expectEqual(@as(u8, 0), unsigned[0]); // no key -> zeroed sig
}
@@ -181,8 +229,47 @@ test "scoreSigMessage: canonical bytes are cross-language stable" {
// The Python SDK (score_signature) and the telemetry worker recompute
// this byte-for-byte; {d:.6} drifting would silently break every sig.
var buf: [512]u8 = undefined;
- const msg = scoreSigMessage(&buf, "a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash").?;
- try std.testing.expectEqualStrings("v1\na1b2\nc3d4\n0.500000\nrun1\nreplay-v1\nart\nevalhash", msg);
- const empty = scoreSigMessage(&buf, "a1b2", "", 1.0, "", "", "", "").?;
- try std.testing.expectEqualStrings("v1\na1b2\n\n1.000000\n\n\n\n", empty);
+ const msg = scoreSigMessage(&buf, "a1b2", "c3d4", 0.5, "run1", "replay-v1", "art", "evalhash", "reviewer", "frontier").?;
+ try std.testing.expectEqualStrings("v2\na1b2\nc3d4\n0.500000\nrun1\nreplay-v1\nart\nevalhash\nreviewer\nfrontier", msg);
+ const empty = scoreSigMessage(&buf, "a1b2", "", 1.0, "", "", "", "", "", "").?;
+ try std.testing.expectEqualStrings("v2\na1b2\n\n1.000000\n\n\n\n\n\n", empty);
+}
+
+test "normalizeOutboundScore: [0,1] passes, (1,100] divides, else rejected" {
+ const eps = 1e-12;
+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), normalizeOutboundScore(0).?, eps);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), normalizeOutboundScore(0.5).?, eps);
+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), normalizeOutboundScore(1).?, eps);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.43), normalizeOutboundScore(43).?, eps);
+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), normalizeOutboundScore(100).?, eps);
+ try std.testing.expectEqual(@as(?f64, null), normalizeOutboundScore(100.5));
+ try std.testing.expectEqual(@as(?f64, null), normalizeOutboundScore(-1));
+ try std.testing.expectEqual(@as(?f64, null), normalizeOutboundScore(std.math.nan(f64)));
+}
+
+test "sanitizeMetaField: a niche with an embedded tab signs and round-trips identically" {
+ var buf: [64]u8 = undefined;
+ const niche = sanitizeMetaField(&buf, "code\treviewer\r\n");
+ try std.testing.expectEqualStrings("code reviewer ", niche);
+
+ // Round-trip through scoreEvent's tab-separated prov transport: splitting
+ // on tabs recovers the exact signed bytes, so a verifier recomputes the
+ // same HMAC over the transported attr value.
+ var provbuf: [512]u8 = undefined;
+ const prov = try std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "j1", "art", "evalhash", "mid", niche });
+ var it = std.mem.splitScalar(u8, prov, '\t');
+ _ = it.next(); // judge_id
+ _ = it.next(); // artifact_sha
+ _ = it.next(); // eval_set_hash
+ _ = it.next(); // provider_class
+ const transported = it.next().?;
+ try std.testing.expect(it.next() == null); // sanitized niche added no extra field
+ try std.testing.expectEqualStrings(niche, transported);
+
+ const saved = g_score_key;
+ defer g_score_key = saved;
+ g_score_key = "test-key";
+ const signed = signScore("a1b2", "", 0.5, "run1", "j1", "art", "evalhash", niche, "mid");
+ const verified = signScore("a1b2", "", 0.5, "run1", "j1", "art", "evalhash", transported, "mid");
+ try std.testing.expectEqualStrings(&signed, &verified);
}
diff --git a/src/subagent.zig b/src/subagent.zig
index 4415d345..3ebafa63 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -105,7 +105,13 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
parent_buf = promptFingerprint(ep);
parent_sha = &parent_buf;
};
- t.fleetEvent("propose", niche, &child_fp, parent_sha, providerClass(ctx.provider.model), "", 0, so);
+ // Oversized genomes skip the propose (review F6): the server verifies
+ // the fingerprint over the carried text, so a truncated genome would
+ // be dropped there anyway — and the fingerprint the scores reference
+ // stays computed over the full text.
+ if (so.len <= telemetry.Telemetry.max_propose_text)
+ t.fleetEvent("propose", niche, &child_fp, parent_sha, providerClass(ctx.provider.model), "", 0, so)
+ else if (ctx.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");
};
// Stable id + sprite for this child's card and its inspectable detail file.
const ordinal = cards.g_subagent_seq.fetchAdd(1, .monotonic);
@@ -251,16 +257,44 @@ pub fn scoreVariants(
if (jout.is_error) continue;
const s = repl_glue.parseEvalScore(jout.text) orelse continue;
if (s <= 0) continue; // skip the total-failure 0 (don't pollute the cell mean), mirroring runEval
+ if (s > 100) {
+ // Review F8: parseEvalScore does NOT return 0-100 by construction
+ // (a stray "score: 9000" line parses as 9000) — guard to [0,100]
+ // here, mirroring mainloop /score's explicit rejection. Skip the
+ // score AND its paired propose/submit so no s01 > 1 row is ever
+ // signed and the submit counter stays in sync with stored scores.
+ if (ctx.tracer) |tr| tr.note("fleet", "score skipped: eval score outside [0,100]");
+ continue;
+ }
+ // SCORE SCALE CONTRACT (issue #168 Gap 4): s is guarded to (0,100]
+ // above; every score that leaves the client is [0,1], so divide at
+ // the emission boundary — s01 is what gets signed and sent.
+ const s01 = s / 100.0;
const genome_fp = promptFingerprint(overrides[i].?);
const esh_fp = promptFingerprint(raws[i]);
const genome: []const u8 = &genome_fp;
const esh: []const u8 = &esh_fp;
- const sig = signScore(genome, "", s, run_id, "", "", esh);
+ // Truncated to 64 chars and sanitized (tab/newline/CR → ' ', review
+ // F7) BEFORE signing (fleetEvent's own niche cap, same as mainloop
+ // /score and runEval) so signed bytes equal ingested bytes.
+ var niche_buf: [64]u8 = undefined;
+ const niche = scoring.sanitizeMetaField(&niche_buf, util.utf8Prefix(niches[i], 64));
+ const sig = signScore(genome, "", s01, run_id, "", "", esh, niche, pclass);
const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
var provbuf: [512]u8 = undefined;
- const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, "" }) catch "";
- t.scoreEvent(genome, "", s, run_id, sig_s, prov);
- t.fleetEvent("submit", niches[i], genome, "", pclass, esh, 0, "");
+ const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche }) catch "";
+ // Genome-send (issue #168 Gap 5), mirroring runEval: ride the variant's
+ // text over on a propose (deduped by fingerprint server-side) so the
+ // scored cell has a servable genome even when runSub never proposed it.
+ // Oversized genomes skip the propose (review F6): a truncated genome
+ // would fail the server's fingerprint check and be dropped anyway.
+ if (niche.len > 0) {
+ if (overrides[i].?.len <= telemetry.Telemetry.max_propose_text)
+ t.fleetEvent("propose", niche, genome, "", pclass, "", 0, overrides[i].?)
+ else if (ctx.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");
+ }
+ t.scoreEvent(genome, "", s01, run_id, sig_s, prov);
+ t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
}
}
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 0acd3bd5..074e5c05 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -21,6 +21,10 @@ const util = @import("util.zig");
const utf8Prefix = util.utf8Prefix;
const unixMs = util.unixMs;
+// For the session run id (score/run join key) and the propose-site
+// fingerprint check. No cycle: scoring imports only std + pricing.
+const scoring = @import("scoring.zig");
+
const root = @import("main.zig");
const harness_version = root.harness_version;
@@ -180,18 +184,44 @@ pub const Telemetry = struct {
const pdup = if (parent.len > 0) self.gpa.dupe(u8, parent[0..@min(parent.len, 32)]) catch "" else "";
const rdup = if (run_id.len > 0) self.gpa.dupe(u8, run_id[0..@min(run_id.len, 64)]) catch "" else "";
const sdup = if (sig.len > 0) self.gpa.dupe(u8, sig[0..@min(sig.len, 64)]) catch "" else "";
- const vdup = if (prov.len > 0) self.gpa.dupe(u8, utf8Prefix(prov, 256)) catch "" else "";
+ // 320, not 256: a max-length prov (64+64+64 signed Step-0 fields +
+ // pclass + a 64-char niche + 4 tabs = 268) must never truncate —
+ // niche/provider_class are folded into the v2 HMAC (issue #168
+ // Gap 2), so a clipped niche would break signature verification.
+ const vdup = if (prov.len > 0) self.gpa.dupe(u8, utf8Prefix(prov, 320)) catch "" else "";
self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "score", .detail = dup, .extra = pdup, .run_id = rdup, .sig = sdup, .prov = vdup, .score = value });
}
self.maybeFlushEvents();
}
+ /// Full-genome cap for a fleet:propose (issue #168 review F6): 64 KiB.
+ /// The backend validates a propose by recomputing the fingerprint over
+ /// the carried prompt_text, so a truncated genome never matches its
+ /// claimed prompt_sha and is dropped server-side — never send one.
+ /// Personas over the cap skip the propose entirely; call sites holding a
+ /// tracer note the skip ("propose skipped: genome > 64KB").
+ pub const max_propose_text = 64 * 1024;
+
/// Record a federated-fleet signal (docs/hyperagents.md §9): propose /
/// submit / elite_pull. body="fleet" with a kind attr, mirroring the SDK
/// _fleet_signal so the worker counts every client identically. signal is a
/// static literal; the rest are duped/truncated like scoreEvent.
pub fn fleetEvent(self: *Telemetry, signal: []const u8, niche: []const u8, prompt_sha: []const u8, parent_sha: []const u8, provider_class: []const u8, eval_set_hash: []const u8, n_elites: i64, prompt_text: []const u8) void {
if (!self.on() or !root.g_fleet) return;
+ // Review F6: never ship a truncated genome — skip the propose instead
+ // (the fingerprint the scores reference stays computed over the full
+ // text; only the genome-send is dropped).
+ if (std.mem.eql(u8, signal, "propose") and prompt_text.len > max_propose_text) return;
+ // Propose-site integrity (issue #168 Gap 3, debug builds only): the
+ // genome text must hash to the fingerprint it claims — a promoted
+ // cell would otherwise serve text that never earned its scores. This
+ // asserts on exactly what will be sent: oversized proposes returned
+ // above, so the utf8Prefix cap below can no longer truncate a genome.
+ // The backend independently recomputes and rejects mismatches.
+ if (builtin.mode == .Debug and std.mem.eql(u8, signal, "propose") and prompt_text.len > 0 and prompt_sha.len > 0) {
+ const fp = scoring.promptFingerprint(prompt_text);
+ std.debug.assert(std.mem.eql(u8, &fp, prompt_sha));
+ }
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
@@ -203,7 +233,7 @@ pub const Telemetry = struct {
self.gpa.dupe(u8, std.fmt.bufPrint(&pbuf, "{s}\t{s}", .{ provider_class, eval_set_hash }) catch "") catch ""
else
"";
- const dtext = if (prompt_text.len > 0) self.gpa.dupe(u8, utf8Prefix(prompt_text, 8192)) catch "" else "";
+ const dtext = if (prompt_text.len > 0) self.gpa.dupe(u8, utf8Prefix(prompt_text, max_propose_text)) catch "" else "";
self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "fleet", .kind = signal, .detail = ddet, .extra = dnic, .run_id = dpar, .prov = provdup, .tasks = n_elites, .text = dtext });
}
self.maybeFlushEvents();
@@ -219,12 +249,17 @@ pub const Telemetry = struct {
defer self.mutex.unlock(self.io);
const dsha = self.gpa.dupe(u8, sha[0..@min(sha.len, 32)]) catch "";
const dtools = if (tools.len > 0) self.gpa.dupe(u8, utf8Prefix(tools, 600)) catch "" else "";
+ // Session run id (issue #168 Gap 6): stamp the same run_id score
+ // records carry so operational outcome (duration/tools/success)
+ // and evaluation fitness share a stable join key per execution.
+ const drun = self.gpa.dupe(u8, &scoring.g_run_id) catch "";
self.push(.{
.t_ms = self.elapsedMsLocked(),
.body = "run",
.kind = if (variant) "variant" else "default",
.detail = dsha,
.extra = dtools,
+ .run_id = drun,
.ms = ms,
.flag = ok,
});
@@ -449,6 +484,9 @@ pub const Telemetry = struct {
try attr(&s, "variant", .{ .int = @intFromBool(std.mem.eql(u8, e.kind, "variant")) });
try attr(&s, "ok", .{ .int = @intFromBool(e.flag) });
try attr(&s, "duration_ms", .{ .int = e.ms });
+ // Session run id (issue #168 Gap 6): the same run_id score
+ // records carry, so outcome and fitness rows join per execution.
+ if (e.run_id.len > 0) try attr(&s, "run_id", .{ .str = e.run_id });
if (e.extra.len > 0) try attr(&s, "tools", .{ .str = e.extra });
} else if (std.mem.eql(u8, e.body, "fleet")) {
try attr(&s, "kind", .{ .str = e.kind });
@@ -580,3 +618,33 @@ test "telemetry writeOtlp emits a fleet record with kind + split prov attrs" {
try std.testing.expect(std.mem.indexOf(u8, out, "\"frontier\"") != null); // provider_class (split from prov)
try std.testing.expect(std.mem.indexOf(u8, out, "\"a9134381\"") != null); // eval_set_hash (split from prov)
}
+test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {
+ var t: Telemetry = .{
+ .io = undefined, // writeOtlp(.., include_summary=false) never touches io
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = undefined,
+ .start_unix_ms = 0,
+ };
+ const events = [_]Telemetry.Event{.{
+ .t_ms = 0,
+ .body = "run",
+ .kind = "default",
+ .detail = "abcd1234", // prompt_sha
+ .extra = "read,edit", // tools
+ .run_id = "cafef00dcafef00d",
+ .ms = 42,
+ .flag = true,
+ }};
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ try t.writeOtlp(&aw.writer, &events, false);
+ const out = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"stringValue\":\"run\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "run_id") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"cafef00dcafef00d\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"read,edit\"") != null); // tools
+}