@igorjpimenta/brayer 2026.11.7 → 2026.11.22-beta.1

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.
@@ -0,0 +1,106 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { flagValue } from "./args.js";
5
+
6
+ export function parseJsonc(text) {
7
+ let out = "";
8
+ let inString = false;
9
+ let escaped = false;
10
+ for (let i = 0; i < text.length; i += 1) {
11
+ const ch = text[i];
12
+ const next = text[i + 1];
13
+ if (inString) {
14
+ out += ch;
15
+ if (escaped) escaped = false;
16
+ else if (ch === "\\") escaped = true;
17
+ else if (ch === '"') inString = false;
18
+ continue;
19
+ }
20
+ if (ch === '"') { inString = true; out += ch; continue; }
21
+ if (ch === "/" && next === "/") {
22
+ while (i < text.length && text[i] !== "\n") i += 1;
23
+ out += "\n";
24
+ continue;
25
+ }
26
+ if (ch === "/" && next === "*") {
27
+ i += 2;
28
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
29
+ i += 1;
30
+ continue;
31
+ }
32
+ out += ch;
33
+ }
34
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
35
+ }
36
+
37
+ function resolveConfigPath(explicit, env) {
38
+ if (explicit) return explicit;
39
+ if (env.OPENCODE_CONFIG) return env.OPENCODE_CONFIG;
40
+ const base = path.join(os.homedir(), ".config", "opencode");
41
+ for (const name of ["opencode.json", "opencode.jsonc"]) {
42
+ const candidate = path.join(base, name);
43
+ if (existsSync(candidate)) return candidate;
44
+ }
45
+ return path.join(base, "opencode.jsonc");
46
+ }
47
+
48
+ function pluginConfigured(plugins) {
49
+ return Array.isArray(plugins) && plugins.some((entry) =>
50
+ typeof entry === "string" && entry.includes("brayer-opencode")
51
+ );
52
+ }
53
+
54
+ async function healthCheck(url) {
55
+ if (!url) return { name: "http health", ok: true, detail: "skipped (no --url)" };
56
+ try {
57
+ const res = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(1500) });
58
+ if (!res.ok) return { name: "http health", ok: false, detail: `${url} -> ${res.status}` };
59
+ const body = await res.json();
60
+ return { name: "http health", ok: body?.ok === true, detail: `${url} -> ${JSON.stringify(body)}` };
61
+ } catch (err) {
62
+ return { name: "http health", ok: false, detail: `${url}: ${err?.message ?? err}` };
63
+ }
64
+ }
65
+
66
+ export async function runDoctor({ rest = [], env = process.env, logger = console } = {}) {
67
+ const harness = flagValue(rest, "--harness") ?? "opencode";
68
+ const configPath = resolveConfigPath(flagValue(rest, "--config"), env);
69
+ const checks = [];
70
+
71
+ let config = null;
72
+ try {
73
+ config = parseJsonc(readFileSync(configPath, "utf8"));
74
+ checks.push({ name: "identity config", ok: true, detail: configPath });
75
+ } catch (err) {
76
+ checks.push({ name: "identity config", ok: false, detail: `${configPath}: ${err?.message ?? err}` });
77
+ }
78
+
79
+ const url = flagValue(rest, "--url") ?? config?.mcp?.brayer?.url ?? "http://127.0.0.1:38293";
80
+
81
+ if (config) {
82
+ const mcp = config?.mcp?.brayer;
83
+ checks.push({
84
+ name: "brayer MCP",
85
+ ok: Boolean(mcp && (mcp.url || mcp.command)),
86
+ detail: mcp ? (mcp.url ?? mcp.command) : "missing mcp.brayer",
87
+ });
88
+ checks.push({
89
+ name: "identity plugin",
90
+ ok: pluginConfigured(config?.plugin),
91
+ detail: pluginConfigured(config?.plugin)
92
+ ? "brayer-opencode loaded"
93
+ : "missing @igorjpimenta/brayer-opencode — bare MCP calls fail identity stamping",
94
+ });
95
+ }
96
+
97
+ checks.push(await healthCheck(url));
98
+
99
+ if (rest.includes("--json")) {
100
+ console.log(JSON.stringify({ harness, config: configPath, checks }, null, 2));
101
+ } else {
102
+ for (const check of checks) logger.log(`${check.ok ? "PASS" : "FAIL"} ${check.name.padEnd(16)} ${check.detail}`);
103
+ }
104
+ const ok = checks.every((check) => check.ok);
105
+ return { harness, config: configPath, checks, ok };
106
+ }
package/src/cli/format.js CHANGED
@@ -1,3 +1,35 @@
1
+ function formatMetric(card) {
2
+ if (card.value == null) return "n/a";
3
+ if (card.unit === "ratio") return `${(card.value * 100).toFixed(1)}%`;
4
+ if (card.unit === "ms") return `${(card.value / 1000).toFixed(1)}s`;
5
+ if (card.unit === "orders") return card.value.toFixed(1);
6
+ return String(card.value);
7
+ }
8
+
9
+ function formatTarget(card) {
10
+ if (card.unit === "ratio") return `${(card.target * 100).toFixed(0)}%`;
11
+ if (card.unit === "ms") return `${(card.target / 1000).toFixed(0)}s`;
12
+ if (card.unit === "orders") return String(card.target);
13
+ return String(card.target);
14
+ }
15
+
16
+ export function formatAdoption(report) {
17
+ const header = `${report.harness} adoption — last ${report.windowDays} days`;
18
+ const rows = report.scorecard.map((card) => [
19
+ card.ok ? "PASS" : "FAIL",
20
+ card.label,
21
+ formatMetric(card),
22
+ card.lowerIsBetter ? `≤ ${formatTarget(card)}` : `≥ ${formatTarget(card)}`,
23
+ ]);
24
+ const widths = [4, Math.max(...rows.map((r) => r[1].length)), 6, 7];
25
+ const lines = [
26
+ `${header}: ${report.claims.total} claims, ${report.attempts.total} attempts, ${report.leaseExpiries} lease expiries`,
27
+ "",
28
+ ...rows.map((r) => `${r[0].padEnd(widths[0])} ${r[1].padEnd(widths[1])} ${r[2].padStart(widths[2])} ${r[3].padStart(widths[3])}`),
29
+ ];
30
+ return lines.join("\n");
31
+ }
32
+
1
33
  export function formatStatus(orders) {
2
34
  if (!orders.length) return "No work orders.";
3
35
  const rows = orders.map((o) => [
package/src/cli/index.js CHANGED
@@ -5,6 +5,9 @@ import { runServe } from "./serve.js";
5
5
  import { runStatus } from "./status.js";
6
6
  import { runSweep } from "./sweep.js";
7
7
  import { runWebhook } from "./webhook.js";
8
+ import { runOrder } from "./order.js";
9
+ import { runAdoption } from "./adoption.js";
10
+ import { runDoctor } from "./doctor.js";
8
11
 
9
12
  const usage = `brayer ${VERSION}
10
13
 
@@ -14,7 +17,12 @@ Usage:
14
17
  brayer serve --mcp http --port 38293 [--host 127.0.0.1]
15
18
  brayer serve --ws --port 38294
16
19
  brayer status [--json]
20
+ brayer adoption [--days N] [--harness H] [--json]
21
+ brayer doctor [--harness H] [--config PATH] [--url URL] [--json]
17
22
  brayer sweep [--max-attempts N]
23
+ brayer order create --title T --goal G --acceptance A [--workspace W] [--status ready]
24
+ brayer order cancel --id ID [--reason R]
25
+ brayer order get --id ID
18
26
  brayer webhook set --harness H --url U [--bearer B] [--timeout-ms N]
19
27
  brayer webhook list
20
28
  brayer webhook remove --harness H
@@ -46,6 +54,22 @@ export async function main(argv = process.argv.slice(2), { env = process.env, lo
46
54
  return;
47
55
  }
48
56
 
57
+ if (command === "adoption") {
58
+ await runAdoption({ rest, env, logger });
59
+ return;
60
+ }
61
+
62
+ if (command === "doctor") {
63
+ const result = await runDoctor({ rest, env, logger });
64
+ if (result && result.ok === false) process.exitCode = 1;
65
+ return;
66
+ }
67
+
68
+ if (command === "order") {
69
+ await runOrder({ rest, env, logger });
70
+ return;
71
+ }
72
+
49
73
  if (command === "sweep") {
50
74
  await runSweep({ args: rest, env, logger });
51
75
  return;
@@ -0,0 +1,56 @@
1
+ import { createStore } from "../store.js";
2
+ import { flagMap } from "./args.js";
3
+
4
+ export async function runOrder({ rest = [], env = process.env, logger = console } = {}) {
5
+ const [sub, ...orderArgs] = rest;
6
+ const values = flagMap(orderArgs);
7
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
8
+ try {
9
+ if (sub === "create") {
10
+ const order = store.order.create({
11
+ title: values.title,
12
+ goal: values.goal,
13
+ acceptance: values.acceptance,
14
+ constraints: values.constraints,
15
+ workspace: values.workspace,
16
+ repo: values.repo,
17
+ branch: values.branch,
18
+ priority: values.priority === undefined ? 50 : Number(values.priority),
19
+ status: values.status ?? "draft",
20
+ approvalMode: values["approval-mode"] ?? "human",
21
+ actor: values.actor ?? "operator",
22
+ });
23
+ console.log(JSON.stringify({ order }, null, 2));
24
+ return order;
25
+ }
26
+
27
+ if (sub === "cancel") {
28
+ if (!values.id) throw new Error("brayer: order cancel requires --id");
29
+ const result = store.order.cancel({
30
+ id: values.id,
31
+ actor: values.actor ?? "operator",
32
+ reason: values.reason ?? "cancelled",
33
+ });
34
+ console.log(JSON.stringify(result, null, 2));
35
+ return result;
36
+ }
37
+
38
+ if (sub === "get") {
39
+ if (!values.id) throw new Error("brayer: order get requires --id");
40
+ const order = store.order.get(values.id);
41
+ if (!order) throw new Error(`brayer: order not found: ${values.id}`);
42
+ console.log(JSON.stringify({
43
+ order,
44
+ events: store.event.list({ workOrderId: order.id }),
45
+ checkpoint: store.checkpoint.latest({ workOrderId: order.id }),
46
+ evidence: store.evidence.list({ workOrderId: order.id }),
47
+ verdicts: store.verdict.list({ workOrderId: order.id }),
48
+ }, null, 2));
49
+ return order;
50
+ }
51
+
52
+ throw new Error("brayer: order requires create, cancel or get");
53
+ } finally {
54
+ store.close();
55
+ }
56
+ }
package/src/config.js CHANGED
@@ -12,6 +12,8 @@ const DEFAULTS = {
12
12
  claimWebhookBearer: "",
13
13
  claimWebhookTimeoutMs: 3000,
14
14
  claimWebhooks: {},
15
+ requireCheckpoint: false,
16
+ requireUsage: false,
15
17
  };
16
18
 
17
19
  const ENV_KEYS = {
@@ -24,9 +26,12 @@ const ENV_KEYS = {
24
26
  claimWebhookUrl: "BRAYER_CLAIM_WEBHOOK_URL",
25
27
  claimWebhookBearer: "BRAYER_CLAIM_WEBHOOK_BEARER",
26
28
  claimWebhookTimeoutMs: "BRAYER_CLAIM_WEBHOOK_TIMEOUT_MS",
29
+ requireCheckpoint: "BRAYER_REQUIRE_CHECKPOINT",
30
+ requireUsage: "BRAYER_REQUIRE_USAGE",
27
31
  };
28
32
 
29
33
  const INT_KEYS = new Set(["leaseSeconds", "maxAttempts", "httpPort", "wsPort", "claimWebhookTimeoutMs"]);
34
+ const BOOL_KEYS = new Set(["requireCheckpoint", "requireUsage"]);
30
35
 
31
36
  function parseInteger(key, value) {
32
37
  const n = Number(value);
@@ -34,6 +39,14 @@ function parseInteger(key, value) {
34
39
  return n;
35
40
  }
36
41
 
42
+ function parseBoolean(key, value) {
43
+ if (typeof value === "boolean") return value;
44
+ const raw = String(value).trim().toLowerCase();
45
+ if (["1", "true", "yes", "on"].includes(raw)) return true;
46
+ if (["0", "false", "no", "off", ""].includes(raw)) return false;
47
+ throw new Error(`brayer: ${key} must be a boolean`);
48
+ }
49
+
37
50
  export function resolveConfig({ explicit = {}, env = process.env } = {}) {
38
51
  for (const key of Object.keys(explicit)) {
39
52
  if (!(key in DEFAULTS)) throw new Error(`brayer: unknown config key: ${key}`);
@@ -57,6 +70,7 @@ export function resolveConfig({ explicit = {}, env = process.env } = {}) {
57
70
  }
58
71
 
59
72
  for (const key of INT_KEYS) out[key] = parseInteger(key, out[key]);
73
+ for (const key of BOOL_KEYS) out[key] = parseBoolean(key, out[key]);
60
74
  return out;
61
75
  }
62
76
 
package/src/identity.js CHANGED
@@ -1,12 +1,9 @@
1
- // A usable layer names something: non-empty, and neither of the tokens no
2
- // key may carry ("unknown", "any", "instance:*" — "any" was the shared-HTTP
3
- // env sentinel; the header mint makes it meaningless as a harness name).
1
+ // A usable layer names something: non-empty. No name is blocked here — a
2
+ // declared harness only has to be deliverable, which the claim gate checks
3
+ // against the register of wake routes (webhook_targets / claimWebhooks) at
4
+ // claim time, not by guessing meanings from the name.
4
5
  function isUsableLayer(v) {
5
- return (
6
- typeof v === "string" &&
7
- v.trim() !== "" &&
8
- !/^(unknown|any|instance:.*)$/i.test(v.trim())
9
- );
6
+ return typeof v === "string" && v.trim() !== "";
10
7
  }
11
8
 
12
9
  // The declaration arrives only from the caller side — never from process env.
@@ -20,9 +17,6 @@ export function assertDeclaration(base = {}) {
20
17
  if (typeof harness !== "string" || !harness.trim()) {
21
18
  throw new Error("brayer: harness must be declared (BRAYER_HARNESS env for stdio serve, X-Brayer-Harness header for HTTP)");
22
19
  }
23
- if (!isUsableLayer(harness)) {
24
- throw new Error(`brayer: refused declaration (reserved: harness). "${harness}" cannot identify a consumer — declare the real harness name.`);
25
- }
26
20
  return { ...base, harness: harness.trim() };
27
21
  }
28
22
 
@@ -44,13 +38,14 @@ export function resolveIdentity({ meta, args, base } = {}) {
44
38
  ? { agent: aAgent, session: aSession, via: "args" }
45
39
  : null;
46
40
  if (!pair) {
41
+ const hint = "Install @igorjpimenta/brayer-opencode (or the matching harness plugin) so identity is stamped automatically, or pass both brayer_agent and brayer_session.";
47
42
  if ((mAgent || aAgent) && (mSession || aSession)) {
48
- throw new Error("brayer: refused caller identity (halves in different channels — pairs never splice). Stamp a whole agent+session pair in one channel: _meta.brayer or brayer_agent/brayer_session args.");
43
+ throw new Error(`brayer: refused caller identity (halves in different channels — pairs never splice). ${hint}`);
49
44
  }
50
45
  const bad = [];
51
46
  if (!mAgent && !aAgent) bad.push("agent");
52
47
  if (!mSession && !aSession) bad.push("session");
53
- throw new Error(`brayer: ${bad.join(" and ")} must be stamped on the call`);
48
+ throw new Error(`brayer: ${bad.join(" and ")} must be stamped on the call. ${hint}`);
54
49
  }
55
50
 
56
51
  return { harness: declared.harness, agent: pair.agent, session: pair.session, via: pair.via };
package/src/mcp.js CHANGED
@@ -55,6 +55,11 @@ function safeEqual(a, b) {
55
55
  return ab.length === bb.length && timingSafeEqual(ab, bb);
56
56
  }
57
57
 
58
+ function isLoopback(req) {
59
+ const addr = req.socket?.remoteAddress ?? "";
60
+ return addr === "127.0.0.1" || addr === "::1" || addr === "::ffff:127.0.0.1";
61
+ }
62
+
58
63
  export async function startMcpHttpServer({
59
64
  store,
60
65
  base,
@@ -85,6 +90,40 @@ export async function startMcpHttpServer({
85
90
  await entry.transport.handleRequest(req, res, body);
86
91
  }
87
92
 
93
+ async function handleRegistration(req, res) {
94
+ if (req.method !== "POST") {
95
+ res.writeHead(405, { allow: "POST", "content-type": "application/json" });
96
+ res.end(JSON.stringify({ error: "method not allowed" }));
97
+ return;
98
+ }
99
+ if (!isLoopback(req)) {
100
+ res.writeHead(403, { "content-type": "application/json" });
101
+ res.end(JSON.stringify({ error: "registration is loopback-only" }));
102
+ return;
103
+ }
104
+ let body;
105
+ try {
106
+ body = await readBody(req);
107
+ } catch {
108
+ res.writeHead(400, { "content-type": "application/json" });
109
+ res.end(JSON.stringify({ error: "invalid json body" }));
110
+ return;
111
+ }
112
+ try {
113
+ const target = store.webhook.upsert({
114
+ harness: body?.harness,
115
+ url: body?.url,
116
+ bearer: body?.bearer ?? null,
117
+ timeoutMs: body?.timeoutMs ?? null,
118
+ });
119
+ res.writeHead(201, { "content-type": "application/json" });
120
+ res.end(JSON.stringify({ ok: true, harness: target.harness, url: target.url }));
121
+ } catch (err) {
122
+ res.writeHead(400, { "content-type": "application/json" });
123
+ res.end(JSON.stringify({ error: String(err?.message ?? err) }));
124
+ }
125
+ }
126
+
88
127
  const server = http.createServer(async (req, res) => {
89
128
  if (req.url === "/health") {
90
129
  res.writeHead(200, { "content-type": "application/json" });
@@ -92,6 +131,10 @@ export async function startMcpHttpServer({
92
131
  return;
93
132
  }
94
133
  const pathname = new URL(req.url, "http://localhost").pathname;
134
+ if (pathname === "/api/brayer/webhooks") {
135
+ await handleRegistration(req, res);
136
+ return;
137
+ }
95
138
  if (pathname !== "/mcp") {
96
139
  res.writeHead(404, { "content-type": "application/json" });
97
140
  res.end(JSON.stringify({ error: "not found" }));
@@ -123,8 +166,8 @@ export async function startMcpHttpServer({
123
166
  return;
124
167
  }
125
168
 
126
- // New session: read the declared harness, refuse unusable names, then
127
- // mint the session-scoped server and register it by response header.
169
+ // New session: read the declared harness, refuse an empty one, then mint
170
+ // the session-scoped server and register it by response header.
128
171
  const header = req.headers["x-brayer-harness"];
129
172
  const headerValue = Array.isArray(header) ? header[0] : header;
130
173
  let minted;
@@ -132,7 +175,7 @@ export async function startMcpHttpServer({
132
175
  minted = assertDeclaration({ harness: headerValue });
133
176
  } catch {
134
177
  res.writeHead(400, { "content-type": "application/json" });
135
- res.end(JSON.stringify({ error: "missing or reserved X-Brayer-Harness" }));
178
+ res.end(JSON.stringify({ error: "missing X-Brayer-Harness" }));
136
179
  return;
137
180
  }
138
181
  const mcp = createMcpServer({ store, base: minted, logger });
@@ -0,0 +1,118 @@
1
+ const DAY_MS = 24 * 60 * 60 * 1000;
2
+
3
+ function median(values) {
4
+ const sorted = [...values].sort((a, b) => a - b);
5
+ if (sorted.length === 0) return null;
6
+ const mid = Math.floor(sorted.length / 2);
7
+ return sorted.length % 2 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2);
8
+ }
9
+
10
+ function ratio(n, d) {
11
+ return d > 0 ? n / d : null;
12
+ }
13
+
14
+ export function createAdoptionApi({ db }) {
15
+ return {
16
+ report({ days = 30, now: at = Date.now(), harness = "opencode" } = {}) {
17
+ const since = at - days * DAY_MS;
18
+ const like = `${harness}:%`;
19
+
20
+ // A "real" order carries a workspace. Proof and gate orders are created
21
+ // without one, so this keeps the scorecard from counting scaffolding as
22
+ // pipeline demand.
23
+ const claims = db.prepare(`
24
+ SELECT e.work_order_id AS workOrderId, e.at AS claimAt, e.actor AS actor,
25
+ w.workspace AS workspace,
26
+ (SELECT MIN(a.at) FROM events a
27
+ WHERE a.work_order_id=e.work_order_id AND a.kind='attempt.started' AND a.at>=e.at) AS attemptAt
28
+ FROM events e
29
+ JOIN work_orders w ON w.id=e.work_order_id
30
+ WHERE e.kind='order.claimed' AND e.actor LIKE ? AND e.at>=?
31
+ ORDER BY e.at ASC
32
+ `).all(like, since);
33
+
34
+ const deltas = [];
35
+ let real = 0;
36
+ let fast = 0;
37
+ let matched = 0;
38
+ for (const claim of claims) {
39
+ if (claim.workspace) real += 1;
40
+ if (claim.attemptAt == null) continue;
41
+ matched += 1;
42
+ const delta = claim.attemptAt - claim.claimAt;
43
+ deltas.push(delta);
44
+ if (delta <= 5 * 60 * 1000) fast += 1;
45
+ }
46
+
47
+ const attempts = db.prepare(`
48
+ SELECT a.*,
49
+ (SELECT COUNT(*) FROM verdicts v WHERE v.attempt_id=a.id) AS verdicts,
50
+ (SELECT COUNT(*) FROM checkpoints c WHERE c.attempt_id=a.id) AS checkpoints
51
+ FROM attempts a
52
+ WHERE a.harness=? AND a.started_at>=?
53
+ `).all(harness, since);
54
+
55
+ let finished = 0;
56
+ let withVerdict = 0;
57
+ let withCheckpoint = 0;
58
+ let usageReported = 0;
59
+ for (const attempt of attempts) {
60
+ if (attempt.status === "finished") finished += 1;
61
+ if (attempt.verdicts > 0) withVerdict += 1;
62
+ if (attempt.checkpoints > 0) withCheckpoint += 1;
63
+ if ((attempt.tokens_in ?? 0) + (attempt.tokens_out ?? 0) + (attempt.cache_read ?? 0) + (attempt.tool_calls ?? 0) > 0) {
64
+ usageReported += 1;
65
+ }
66
+ }
67
+
68
+ const leaseExpiries = db.prepare(`
69
+ SELECT COUNT(*) AS n
70
+ FROM events r
71
+ WHERE r.kind='order.released' AND r.note='lease expired' AND r.at>=?
72
+ AND (SELECT c.actor FROM events c
73
+ WHERE c.work_order_id=r.work_order_id AND c.kind='order.claimed' AND c.at<=r.at
74
+ ORDER BY c.at DESC LIMIT 1) LIKE ?
75
+ `).get(since, like).n;
76
+
77
+ const realPerWeek = days > 0 ? (real / days) * 7 : 0;
78
+ const medianDelta = median(deltas);
79
+ const claimToAttempt5m = ratio(fast, matched);
80
+ const verdictShare = ratio(withVerdict, attempts.length);
81
+ const usageShare = ratio(usageReported, attempts.length);
82
+ const checkpointShare = ratio(withCheckpoint, attempts.length);
83
+
84
+ const scorecard = [
85
+ { key: "realOrdersPerWeek", label: "Real orders claimed / week", value: realPerWeek, target: 20, ok: realPerWeek >= 20, unit: "orders" },
86
+ { key: "claimToAttempt5m", label: "Claim → attempt within 5 min", value: claimToAttempt5m, target: 0.9, ok: claimToAttempt5m != null && claimToAttempt5m >= 0.9, unit: "ratio" },
87
+ { key: "verdictShare", label: "Attempts with a verdict", value: verdictShare, target: 0.8, ok: verdictShare != null && verdictShare >= 0.8, unit: "ratio" },
88
+ { key: "leaseExpiries", label: "OpenCode lease expiries", value: leaseExpiries, target: 0, ok: leaseExpiries === 0, unit: "count", lowerIsBetter: true },
89
+ { key: "usageShare", label: "Attempts reporting usage", value: usageShare, target: 1, ok: usageShare != null && usageShare >= 1, unit: "ratio" },
90
+ { key: "medianClaimToAttempt", label: "Median claim → attempt", value: medianDelta, target: 2 * 60 * 1000, ok: medianDelta != null && medianDelta < 2 * 60 * 1000, unit: "ms" },
91
+ ];
92
+
93
+ return {
94
+ harness,
95
+ windowDays: days,
96
+ since,
97
+ generatedAt: at,
98
+ claims: {
99
+ total: claims.length,
100
+ real,
101
+ matched,
102
+ within5m: fast,
103
+ medianToAttemptMs: medianDelta,
104
+ },
105
+ attempts: {
106
+ total: attempts.length,
107
+ finished,
108
+ withVerdict,
109
+ withCheckpoint,
110
+ usageReported,
111
+ },
112
+ leaseExpiries,
113
+ rates: { claimToAttempt5m, verdictShare, usageShare, checkpointShare },
114
+ scorecard,
115
+ };
116
+ },
117
+ };
118
+ }
@@ -2,7 +2,7 @@ import { newAttemptId } from "../ids.js";
2
2
  import { now } from "./util.js";
3
3
  import { rowAttempt } from "./rows.js";
4
4
 
5
- export function createAttemptApi({ db, insertEvent, orderApi, clearExpiry }) {
5
+ export function createAttemptApi({ db, insertEvent, orderApi, clearExpiry, cfg = {} }) {
6
6
  const attemptApi = {
7
7
  get(id) {
8
8
  return rowAttempt(db.prepare("SELECT * FROM attempts WHERE id=?").get(id));
@@ -42,6 +42,7 @@ export function createAttemptApi({ db, insertEvent, orderApi, clearExpiry }) {
42
42
  actor: agent, note: "attempt started", sessionRef, at: t,
43
43
  });
44
44
  db.exec("COMMIT");
45
+ clearExpiry?.(workOrderId);
45
46
  return { attempt: attemptApi.get(id), order: orderApi.get(workOrderId), reason: null };
46
47
  } catch (err) {
47
48
  db.exec("ROLLBACK");
@@ -134,6 +135,20 @@ export function createAttemptApi({ db, insertEvent, orderApi, clearExpiry }) {
134
135
  })) {
135
136
  if (!Number.isInteger(value)) throw new Error(`${name} must be an integer`);
136
137
  }
138
+ if (cfg.requireCheckpoint) {
139
+ const linked = nextCheckpointId
140
+ ? db.prepare("SELECT 1 FROM checkpoints WHERE id=? AND attempt_id=?").get(nextCheckpointId, attemptId)
141
+ : db.prepare("SELECT 1 FROM checkpoints WHERE attempt_id=? LIMIT 1").get(attemptId);
142
+ if (!linked) {
143
+ throw new Error("checkpoint is required before finishing an attempt (set BRAYER_REQUIRE_CHECKPOINT=0 to disable)");
144
+ }
145
+ }
146
+ if (cfg.requireUsage) {
147
+ const reported = nextUsage.tokensIn + nextUsage.tokensOut + nextUsage.cacheRead + nextUsage.toolCalls;
148
+ if (reported <= 0) {
149
+ throw new Error("usage must be reported before finishing an attempt (set BRAYER_REQUIRE_USAGE=0 to disable)");
150
+ }
151
+ }
137
152
  db.prepare(`
138
153
  UPDATE attempts
139
154
  SET status=?, ended_at=?, tokens_in=?, tokens_out=?, cache_read=?, cost_usd=?,
@@ -1,9 +1,18 @@
1
1
  import { now } from "./util.js";
2
2
 
3
- export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim, logger }) {
3
+ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim, claimGate, logger }) {
4
4
  const timers = new Map();
5
5
  const MAX_TIMER_MS = 2147483647;
6
6
 
7
+ // The claim must be wake-deliverable: agentId carries harness as its first
8
+ // segment (identityKey = harness:agent:session). A claim nobody could be
9
+ // woken for is invisible work.
10
+ function requireClaimable(agentId) {
11
+ if (!claimGate) return;
12
+ const harness = String(agentId).split(":")[0] ?? "";
13
+ claimGate(harness);
14
+ }
15
+
7
16
  function clearExpiry(id) {
8
17
  const timer = timers.get(id);
9
18
  if (timer) {
@@ -34,6 +43,7 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim, lo
34
43
  claimById({ id, agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
35
44
  if (!id) throw new Error("order id is required");
36
45
  if (!agentId) throw new Error("agentId is required");
46
+ requireClaimable(agentId);
37
47
  const t = now();
38
48
  const expires = t + leaseSeconds * 1000;
39
49
  db.exec("BEGIN IMMEDIATE");
@@ -68,6 +78,7 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim, lo
68
78
 
69
79
  claimNext({ agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
70
80
  if (!agentId) throw new Error("agentId is required");
81
+ requireClaimable(agentId);
71
82
  const candidates = db.prepare(`
72
83
  SELECT id FROM work_orders
73
84
  WHERE status='ready' AND (assignee IS NULL OR assignee=?)
@@ -57,6 +57,38 @@ export function createOrderApi({ db, insertEvent }) {
57
57
  return rowOrder(db.prepare("SELECT * FROM work_orders WHERE id=?").get(id));
58
58
  },
59
59
 
60
+ cancel({ id, actor = "operator", reason = "cancelled" } = {}) {
61
+ if (!id) throw new Error("order id is required");
62
+ const t = now();
63
+ db.exec("BEGIN IMMEDIATE");
64
+ try {
65
+ const cur = rowOrder(db.prepare("SELECT * FROM work_orders WHERE id=?").get(id));
66
+ if (!cur) throw new Error(`order not found: ${id}`);
67
+ if (cur.status === "cancelled") { db.exec("ROLLBACK"); return { order: cur, changed: false }; }
68
+ if (cur.status === "running") {
69
+ throw new Error("cannot cancel a running attempt — finish or fail the attempt first");
70
+ }
71
+ if (["approved", "rejected", "done"].includes(cur.status)) {
72
+ throw new Error(`cannot cancel a ${cur.status} order`);
73
+ }
74
+ db.prepare(`
75
+ UPDATE work_orders
76
+ SET status='cancelled', assignee=NULL, claim_expires_at=NULL, lease_seconds=NULL,
77
+ last_heartbeat=NULL, closed_at=?, updated_at=?
78
+ WHERE id=?
79
+ `).run(t, t, id);
80
+ insertEvent({
81
+ workOrderId: id, fromStatus: cur.status, toStatus: "cancelled", kind: "order.cancelled",
82
+ actor, note: reason, at: t,
83
+ });
84
+ db.exec("COMMIT");
85
+ return { order: orderApi.get(id), changed: true };
86
+ } catch (err) {
87
+ db.exec("ROLLBACK");
88
+ throw err;
89
+ }
90
+ },
91
+
60
92
  list({ status, limit = 100 } = {}) {
61
93
  const sql = status
62
94
  ? "SELECT * FROM work_orders WHERE status=? ORDER BY priority DESC, created_at ASC LIMIT ?"