@chatpanel/gateway 0.6.109 → 0.7.0

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.
Files changed (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2290
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
@@ -1,92 +1 @@
1
- // The agents' scorecards — every fact the runner said about a member, chained and attested
2
- // here, where no client and no agent can write one for itself.
3
- //
4
- // One chain per agent id. A fact arrives as the run store's `task.scored` event (or a
5
- // person's rating through the route); the store makes the entry (scorecard.js: canonical,
6
- // hashed onto the previous), marks it with an HMAC over a key only this process holds, and
7
- // appends. Nothing is ever edited: a correction is a new entry. The file is encrypted at
8
- // rest with the team store's key, like the runs; the attestation key is derived from it
9
- // (HKDF-style label), so the same install attests the same way across restarts and a copied
10
- // file elsewhere cannot forge a mark.
11
- //
12
- // Read: `GET /v1/agents/:id/scorecard` → the chain, its summary, and whether it verifies.
13
-
14
- import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
15
- import { join, dirname } from 'node:path';
16
- import os from 'node:os';
17
- import { createHmac, webcrypto } from 'node:crypto';
18
- import { makeEntry, attest, verifyChain, verifyAttested, summarize, SCORECARD_ENTRY_KINDS } from './scorecard.js';
19
-
20
- const DIR = join(os.homedir(), '.chatpanel');
21
- const STORE_PATH = process.env.CHATPANEL_SCORECARDS_STORE || join(DIR, 'scorecards.json');
22
- const MAX_ENTRIES_PER_AGENT = 5000;
23
-
24
- export class ScorecardStore {
25
- constructor({ storePath = STORE_PATH, key = null, now = () => Date.now() } = {}) {
26
- this.path = storePath;
27
- this.now = now;
28
- // The attestation key: derived from the store key with a label, never the key itself.
29
- this._mark = key ? createHmac('sha256', key).update('chatpanel:scorecard:attest:v1').digest() : null;
30
- this.chains = new Map(); // agentId -> [entries]
31
- this._queue = Promise.resolve(); // appends are serialised: a chain has one head
32
- }
33
- load() {
34
- try {
35
- if (existsSync(this.path)) {
36
- const doc = JSON.parse(readFileSync(this.path, 'utf8'));
37
- for (const [id, entries] of Object.entries(doc?.chains || {})) if (Array.isArray(entries)) this.chains.set(id, entries);
38
- }
39
- } catch { this.chains = new Map(); }
40
- return this;
41
- }
42
- save() {
43
- mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
44
- const tmp = `${this.path}.${process.pid}.tmp`;
45
- writeFileSync(tmp, JSON.stringify({ v: 1, chains: Object.fromEntries(this.chains) }), { mode: 0o600 });
46
- renameSync(tmp, this.path);
47
- }
48
- /** Append one fact to an agent's chain: made, chained, attested, saved. Serialised per store. */
49
- append(fact) {
50
- const run = async () => {
51
- const agentId = String(fact?.agentId || '');
52
- if (!agentId) throw new Error('scorecard: agentId required');
53
- if (!SCORECARD_ENTRY_KINDS.includes(fact?.kind)) throw new Error(`scorecard: kind must be one of ${SCORECARD_ENTRY_KINDS.join(', ')}`);
54
- const chain = this.chains.get(agentId) || [];
55
- if (chain.length >= MAX_ENTRIES_PER_AGENT) throw new Error('scorecard: chain is full');
56
- let entry = await makeEntry({ ...fact, at: fact.at || this.now() }, chain.at(-1) || null, { now: this.now, subtle: webcrypto.subtle });
57
- if (this._mark) entry = await attest(entry, this._mark, { subtle: webcrypto.subtle });
58
- chain.push(entry);
59
- this.chains.set(agentId, chain);
60
- this.save();
61
- return entry;
62
- };
63
- const p = this._queue.then(run, run);
64
- this._queue = p.catch(() => {});
65
- return p;
66
- }
67
- /** The chain, its card, and whether it verifies — what a recruiter (or a person) reads. */
68
- async get(agentId) {
69
- const chain = this.chains.get(String(agentId || '')) || [];
70
- const verified = await verifyChain(chain, { subtle: webcrypto.subtle });
71
- const attested = this._mark ? await verifyAttested(chain, this._mark, { subtle: webcrypto.subtle }) : { ok: false, attested: 0, of: chain.length };
72
- return { agentId: String(agentId || ''), entries: chain, summary: summarize(chain), verified, attested };
73
- }
74
- /** Every agent's card, without the chains. */
75
- list() {
76
- return [...this.chains.entries()].map(([agentId, chain]) => ({ agentId, ...summarize(chain) }));
77
- }
78
- /** A run store event, as the fold sees it: only `task.scored` becomes a fact. */
79
- fromRunEvent(ev, run) {
80
- if (String(ev?.type || '') !== 'task.scored') return null;
81
- const p = ev.payload && typeof ev.payload === 'object' ? ev.payload : {};
82
- if (!p.agentId) return null;
83
- return this.append({
84
- agentId: p.agentId, kind: p.outcome === 'task.failed' ? 'task.failed' : 'task.done', at: ev.at,
85
- runId: run?.id || p.runId, taskId: p.taskId, model: p.model, engine: p.engine, scm: p.scm, size: p.size, roleKind: p.roleKind,
86
- tools: p.tools, with: p.with, refs: p.refs, error: p.error,
87
- ...(run?.projectId ? { projectId: run.projectId } : {}), ...(run?.jobId ? { jobId: run.jobId } : {}),
88
- }).catch(() => null);
89
- }
90
- }
91
-
92
- export function createScorecardStore(opts) { return new ScorecardStore(opts).load(); }
1
+ import{readFileSync as l,writeFileSync as u,existsSync as p,mkdirSync as m,renameSync as f}from"node:fs";import{join as c,dirname as w}from"node:path";import S from"node:os";import{createHmac as y,webcrypto as a}from"node:crypto";import{makeEntry as g,attest as I,verifyChain as b,verifyAttested as k,summarize as h,SCORECARD_ENTRY_KINDS as d}from"./scorecard.js";const E=c(S.homedir(),".chatpanel"),_=process.env.CHATPANEL_SCORECARDS_STORE||c(E,"scorecards.json"),j=5e3;class R{constructor({storePath:e=_,key:s=null,now:t=()=>Date.now()}={}){this.path=e,this.now=t,this._mark=s?y("sha256",s).update("chatpanel:scorecard:attest:v1").digest():null,this.chains=new Map,this._queue=Promise.resolve()}load(){try{if(p(this.path)){const e=JSON.parse(l(this.path,"utf8"));for(const[s,t]of Object.entries(e?.chains||{}))Array.isArray(t)&&this.chains.set(s,t)}}catch{this.chains=new Map}return this}save(){m(w(this.path),{recursive:!0,mode:448});const e=`${this.path}.${process.pid}.tmp`;u(e,JSON.stringify({v:1,chains:Object.fromEntries(this.chains)}),{mode:384}),f(e,this.path)}append(e){const s=async()=>{const r=String(e?.agentId||"");if(!r)throw new Error("scorecard: agentId required");if(!d.includes(e?.kind))throw new Error(`scorecard: kind must be one of ${d.join(", ")}`);const i=this.chains.get(r)||[];if(i.length>=j)throw new Error("scorecard: chain is full");let n=await g({...e,at:e.at||this.now()},i.at(-1)||null,{now:this.now,subtle:a.subtle});return this._mark&&(n=await I(n,this._mark,{subtle:a.subtle})),i.push(n),this.chains.set(r,i),this.save(),n},t=this._queue.then(s,s);return this._queue=t.catch(()=>{}),t}async get(e){const s=this.chains.get(String(e||""))||[],t=await b(s,{subtle:a.subtle}),r=this._mark?await k(s,this._mark,{subtle:a.subtle}):{ok:!1,attested:0,of:s.length};return{agentId:String(e||""),entries:s,summary:h(s),verified:t,attested:r}}list(){return[...this.chains.entries()].map(([e,s])=>({agentId:e,...h(s)}))}fromRunEvent(e,s){if(String(e?.type||"")!=="task.scored")return null;const t=e.payload&&typeof e.payload=="object"?e.payload:{};return t.agentId?this.append({agentId:t.agentId,kind:t.outcome==="task.failed"?"task.failed":"task.done",at:e.at,runId:s?.id||t.runId,taskId:t.taskId,model:t.model,engine:t.engine,scm:t.scm,size:t.size,roleKind:t.roleKind,tools:t.tools,with:t.with,refs:t.refs,error:t.error,...s?.projectId?{projectId:s.projectId}:{},...s?.jobId?{jobId:s.jobId}:{}}).catch(()=>null):null}}function C(o){return new R(o).load()}export{R as ScorecardStore,C as createScorecardStore};
package/src/scorecard.js CHANGED
@@ -1,336 +1 @@
1
- // VENDORED from @chatpanel/events/scorecard.js — edit there, then copy over.
2
- // An agent's scorecard — an immutable record of what it actually did, and matching on it.
3
- //
4
- // A scorecard is a CHAIN of entries, one per fact, append-only: a task it finished (how big,
5
- // with which tools, alongside whom, in which role), a rating a job gave it, an agent it
6
- // created, an interaction. Every entry carries the hash of the one before and its own hash,
7
- // so an edit anywhere breaks every link after it; the gateway's store adds its own mark
8
- // (an HMAC over the hash with a key only the store holds) so an entry a client — or an
9
- // agent — wrote for itself shows as unattested. The facts are produced by the runner and
10
- // attested by the store, never written by the agent: the only way to a better scorecard is
11
- // the work.
12
- //
13
- // `summarize` turns the chain into the card a recruiter reads; `fit` scores an agent type
14
- // against a job's needs with that record — the same function the evaluator starts from, so
15
- // an application's fit has reasons a person can read and overrule.
16
- //
17
- // The model is a variable, not a constant (architecture-pillars.md §13): every task fact also
18
- // says which ENGINE did it — a model endpoint or a harness (a CLI coding agent), and for a
19
- // harness the model it was asked to run — so `summarize` can split the card by engine
20
- // (`byEngine`) and a recruiter can tell an agent that did well on a small model from one
21
- // that was carried by a large one. And where the task ran in a git checkout (§14), the fact
22
- // carries `scm`: the branch and HEAD before and after, commits made, a PR when one was
23
- // opened, and whether it merged — the one outcome that does not come from a judge.
24
- //
25
- // Dependency-free: hashing is `crypto.subtle` (browser, Node, a phone), injectable for tests.
26
-
27
- export const SCORECARD_ENTRY_KINDS = Object.freeze(['task.done', 'task.failed', 'rating', 'created', 'interaction', 'role']);
28
- export const ROLE_KINDS = Object.freeze(['ic', 'orchestrator', 'manager', 'manager-of-managers']);
29
- export const SCORECARD_VERSION = 1;
30
- export const ENGINE_KINDS = Object.freeze(['model', 'harness']);
31
-
32
- /**
33
- * An engine as the record keeps it: `{ kind, id, model?, label? }`. `kind` is `model` (an
34
- * endpoint the client calls) or `harness` (a CLI coding agent the bridge runs — `id` is the
35
- * harness, `model` the model it was asked to run, when one was named). A host that does not
36
- * say the kind gets `model`, which is the honest default for a bare model id. A string is
37
- * an id.
38
- */
39
- export function normalizeEngine(e) {
40
- if (!e) return null;
41
- const src = typeof e === 'string' ? { id: e } : e;
42
- const id = String(src.id || src.harnessId || src.model || '').trim();
43
- if (!id) return null;
44
- const kind = ENGINE_KINDS.includes(src.kind) ? src.kind : (src.harnessId ? 'harness' : 'model');
45
- const model = src.model != null && String(src.model).trim() && String(src.model) !== id ? String(src.model).trim() : undefined;
46
- return { kind, id, ...(model ? { model } : {}), ...(src.label && String(src.label) !== id ? { label: String(src.label).slice(0, 120) } : {}) };
47
- }
48
-
49
- /** One key per engine — what `byEngine` groups on and what the model ledger will be keyed by. */
50
- export function engineKey(e) {
51
- const n = normalizeEngine(e);
52
- return n ? `${n.kind}:${n.id}${n.model ? `/${n.model}` : ''}` : null;
53
- }
54
-
55
- /** What a task did in a checkout, as the record keeps it. Strings clipped, counts rounded. */
56
- export function normalizeScm(s) {
57
- if (!s || typeof s !== 'object') return null;
58
- const str = (v, n = 200) => (v == null || v === '' ? undefined : String(v).slice(0, n));
59
- const out = {
60
- repo: str(s.repo, 300), remote: str(s.remote, 300), base: str(s.base, 120), branch: str(s.branch, 120),
61
- head: str(s.head, 64), headAfter: str(s.headAfter, 64),
62
- commits: s.commits != null ? Math.max(0, Math.round(Number(s.commits) || 0)) : undefined,
63
- pr: str(s.pr, 300),
64
- merged: s.merged === true ? true : s.merged === false ? false : undefined,
65
- dirty: s.dirty === true ? true : s.dirty === false ? false : undefined,
66
- };
67
- for (const k of Object.keys(out)) if (out[k] === undefined) delete out[k];
68
- return Object.keys(out).length ? out : null;
69
- }
70
-
71
- const enc = new TextEncoder();
72
- const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
73
-
74
- /** Canonical JSON: keys sorted at every level, so the same fact hashes the same everywhere. */
75
- export function canonical(v) {
76
- if (v === null || typeof v !== 'object') return JSON.stringify(v);
77
- if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
78
- return `{${Object.keys(v).sort().map((k) => (v[k] === undefined ? null : `${JSON.stringify(k)}:${canonical(v[k])}`)).filter(Boolean).join(',')}}`;
79
- }
80
-
81
- /** SHA-256 over text, as hex; `subtle` is injectable (a runtime without it passes its own). */
82
- export async function sha256(text, { subtle = globalThis.crypto?.subtle } = {}) {
83
- if (!subtle) throw new Error('scorecard: no crypto.subtle — pass one');
84
- return hex(await subtle.digest('SHA-256', enc.encode(String(text))));
85
- }
86
-
87
- /** The fields a hash covers — everything but the hash and the store's mark. */
88
- function hashable(e) {
89
- const { hash: _h, sig: _s, ...rest } = e;
90
- return rest;
91
- }
92
-
93
- /**
94
- * A new entry chained onto `prev` (the last entry, or null for the first). Pure apart from
95
- * the digest: the caller (the store) decides whether it is attested.
96
- */
97
- export async function makeEntry(fact, prev, { now = () => Date.now(), subtle } = {}) {
98
- if (!fact || typeof fact !== 'object') throw new Error('scorecard: an entry needs a fact');
99
- if (!SCORECARD_ENTRY_KINDS.includes(fact.kind)) throw new Error(`scorecard: kind must be one of ${SCORECARD_ENTRY_KINDS.join(', ')}`);
100
- if (!fact.agentId) throw new Error('scorecard: agentId required');
101
- const e = {
102
- v: SCORECARD_VERSION,
103
- seq: prev ? prev.seq + 1 : 0,
104
- agentId: String(fact.agentId),
105
- kind: fact.kind,
106
- at: Number(fact.at) || now(),
107
- ...(fact.projectId ? { projectId: String(fact.projectId) } : {}),
108
- ...(fact.jobId ? { jobId: String(fact.jobId) } : {}),
109
- ...(fact.runId ? { runId: String(fact.runId) } : {}),
110
- ...(fact.taskId ? { taskId: String(fact.taskId) } : {}),
111
- ...(fact.model ? { model: String(fact.model) } : {}),
112
- ...(normalizeEngine(fact.engine) ? { engine: normalizeEngine(fact.engine) } : {}),
113
- ...(normalizeScm(fact.scm) ? { scm: normalizeScm(fact.scm) } : {}),
114
- ...(fact.size ? { size: sizeOf(fact.size) } : {}),
115
- ...(fact.roleKind ? { roleKind: ROLE_KINDS.includes(fact.roleKind) ? fact.roleKind : 'ic' } : {}),
116
- ...(Array.isArray(fact.tools) && fact.tools.length ? { tools: [...new Set(fact.tools.map(String))].sort() } : {}),
117
- ...(Array.isArray(fact.with) && fact.with.length ? { with: [...new Set(fact.with.map(String))].sort() } : {}),
118
- ...(Array.isArray(fact.created) && fact.created.length ? { created: [...new Set(fact.created.map(String))] } : {}),
119
- ...(fact.rating ? { rating: { by: String(fact.rating.by || 'person'), score: clamp01(fact.rating.score), ...(fact.rating.note ? { note: String(fact.rating.note).slice(0, 500) } : {}), ...(fact.rating.about != null ? { about: Number(fact.rating.about) } : {}) } } : {}),
120
- ...(Array.isArray(fact.refs) && fact.refs.length ? { refs: fact.refs.map(String).slice(0, 12) } : {}),
121
- ...(fact.error ? { error: String(fact.error).slice(0, 300) } : {}),
122
- prev: prev ? prev.hash : null,
123
- };
124
- e.hash = await sha256(canonical(hashable(e)), { subtle });
125
- return e;
126
- }
127
-
128
- const clamp01 = (n) => Math.max(0, Math.min(1, Number(n) || 0));
129
- const r3 = (v) => (v == null ? null : Math.round(v * 1000) / 1000);
130
- const sizeOf = (s) => ({ ms: Math.max(0, Math.round(Number(s.ms) || 0)), steps: Math.max(0, Math.round(Number(s.steps) || 0)), tools: Math.max(0, Math.round(Number(s.tools) || 0)), findings: Math.max(0, Math.round(Number(s.findings) || 0)), tokens: Math.max(0, Math.round(Number(s.tokens) || 0)) });
131
-
132
- /** Does every link hold? Returns `{ ok, at }` — `at` is the seq of the first broken entry. */
133
- export async function verifyChain(entries, { subtle } = {}) {
134
- let prev = null;
135
- for (const e of entries || []) {
136
- if (!e || typeof e !== 'object') return { ok: false, at: prev ? prev.seq + 1 : 0, why: 'not an entry' };
137
- if ((prev ? prev.seq + 1 : 0) !== e.seq) return { ok: false, at: e.seq, why: 'seq' };
138
- if ((prev ? prev.hash : null) !== e.prev) return { ok: false, at: e.seq, why: 'prev' };
139
- const h = await sha256(canonical(hashable(e)), { subtle });
140
- if (h !== e.hash) return { ok: false, at: e.seq, why: 'hash' };
141
- prev = e;
142
- }
143
- return { ok: true, at: null, length: (entries || []).length };
144
- }
145
-
146
- /**
147
- * The store's mark. `key` is raw bytes only the store holds; an HMAC-SHA-256 over the hash.
148
- * Anyone can re-hash the chain; only the store can mark it, so an entry written elsewhere
149
- * is honest about being unattested. Injectable `subtle` again.
150
- */
151
- export async function attest(entry, key, { subtle = globalThis.crypto?.subtle } = {}) {
152
- const k = await subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
153
- return { ...entry, sig: hex(await subtle.sign('HMAC', k, enc.encode(entry.hash))) };
154
- }
155
- export async function verifyAttested(entries, key, { subtle = globalThis.crypto?.subtle } = {}) {
156
- const k = await subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
157
- const out = [];
158
- for (const e of entries || []) {
159
- const sig = e?.sig ? new Uint8Array(e.sig.match(/../g).map((x) => parseInt(x, 16))) : null;
160
- out.push(!!sig && await subtle.verify('HMAC', k, sig, enc.encode(e.hash)));
161
- }
162
- return { ok: out.every(Boolean), attested: out.filter(Boolean).length, of: out.length };
163
- }
164
-
165
- /** The card a recruiter reads. */
166
- export function summarize(entries, { recent = 5 } = {}) {
167
- const list = (entries || []).filter((e) => e && e.kind);
168
- const done = list.filter((e) => e.kind === 'task.done');
169
- const failed = list.filter((e) => e.kind === 'task.failed');
170
- const sum = (k) => done.reduce((n, e) => n + (e.size?.[k] || 0), 0);
171
- const largest = done.reduce((m, e) => Math.max(m, e.size?.steps || 0), 0);
172
- const tools = new Set(); const withAgents = new Set(); const created = new Set();
173
- const roles = { ic: 0, orchestrator: 0, manager: 0, 'manager-of-managers': 0 };
174
- const models = new Map();
175
- // Per engine: how many tasks, how they went, how big, and the ratings that were ABOUT a
176
- // task on it. A rating names its task by `about` (the seq of the entry it rates), by
177
- // taskId, or — failing both — by runId when that run had exactly one task on the card.
178
- const engines = new Map(); // key -> { engine, tasks, done, failed, tokens, ratings[] }
179
- const engineOfEntry = new Map(); // seq -> key
180
- const byTask = new Map(); const byRun = new Map(); // taskId -> seq, runId -> [seq]
181
- const scm = { tasks: 0, commits: 0, prs: 0, merged: 0 };
182
- for (const e of list) {
183
- for (const t of e.tools || []) tools.add(t);
184
- for (const a of e.with || []) withAgents.add(a);
185
- for (const a of e.created || []) created.add(a);
186
- if (e.roleKind && (e.kind === 'task.done' || e.kind === 'task.failed' || e.kind === 'role')) roles[e.roleKind] = (roles[e.roleKind] || 0) + 1;
187
- if (e.model) models.set(e.model, (models.get(e.model) || 0) + 1);
188
- if (e.kind === 'task.done' || e.kind === 'task.failed') {
189
- const key = engineKey(e.engine);
190
- if (key) {
191
- const row = engines.get(key) || { engine: normalizeEngine(e.engine), tasks: 0, done: 0, failed: 0, tokens: 0, ratings: [] };
192
- row.tasks += 1; row[e.kind === 'task.done' ? 'done' : 'failed'] += 1; row.tokens += e.size?.tokens || 0;
193
- engines.set(key, row);
194
- engineOfEntry.set(e.seq, key);
195
- if (e.taskId) byTask.set(`${e.runId || ''}/${e.taskId}`, e.seq);
196
- if (e.runId) byRun.set(e.runId, [...(byRun.get(e.runId) || []), e.seq]);
197
- }
198
- if (e.scm) { scm.tasks += 1; scm.commits += e.scm.commits || 0; if (e.scm.pr) scm.prs += 1; if (e.scm.merged) scm.merged += 1; }
199
- }
200
- }
201
- for (const e of list) {
202
- if (e.kind !== 'rating' || !e.rating) continue;
203
- const seq = e.rating.about != null ? e.rating.about
204
- : e.taskId && byTask.has(`${e.runId || ''}/${e.taskId}`) ? byTask.get(`${e.runId || ''}/${e.taskId}`)
205
- : e.runId && (byRun.get(e.runId) || []).length === 1 ? byRun.get(e.runId)[0] : null;
206
- const key = seq != null ? engineOfEntry.get(seq) : null;
207
- if (key) engines.get(key).ratings.push(e.rating.score);
208
- }
209
- const mean = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null);
210
- const byEngine = [...engines.values()].sort((a, b) => b.tasks - a.tasks).map((r) => ({
211
- key: engineKey(r.engine), ...r.engine, tasks: r.tasks, done: r.done, failed: r.failed,
212
- failRate: r.tasks ? Math.round((r.failed / r.tasks) * 1000) / 1000 : 0,
213
- tokens: r.tasks ? Math.round(r.tokens / r.tasks) : 0, // mean per task — the cost proxy until the ledger prices it
214
- rating: { avg: mean(r.ratings), count: r.ratings.length },
215
- }));
216
- // 1 − spread of rating across engines it was rated on (≥ 2): low spread = robust to routing;
217
- // high spread = it NEEDS a particular engine, a fact a recruiter respects, not a penalty.
218
- const ratedEngines = byEngine.filter((r) => r.rating.avg != null).map((r) => r.rating.avg);
219
- const engineIndependence = ratedEngines.length >= 2 ? Math.round((1 - (Math.max(...ratedEngines) - Math.min(...ratedEngines))) * 1000) / 1000 : null;
220
- // Leverage (rating above the engine's own mean) and efficiency (rating ÷ cost) wait on the
221
- // model ledger (§13.2, with A1): they need every engine's mean, which one card cannot know.
222
- const ratings = list.filter((e) => e.kind === 'rating' && e.rating).map((e) => e.rating.score);
223
- const avg = ratings.length ? ratings.reduce((a, b) => a + b, 0) / ratings.length : null;
224
- const recentRatings = ratings.slice(-recent);
225
- const refs = [...new Set(list.flatMap((e) => e.refs || []))].slice(-recent);
226
- return {
227
- agentId: list[0]?.agentId || null,
228
- entries: list.length,
229
- jobsDone: done.length,
230
- jobsFailed: failed.length,
231
- size: { ms: sum('ms'), steps: sum('steps'), tools: sum('tools'), findings: sum('findings'), tokens: sum('tokens'), largestSteps: largest },
232
- tools: [...tools].sort(),
233
- workedWith: [...withAgents].sort(),
234
- created: [...created],
235
- roles,
236
- models: [...models.entries()].sort((a, b) => b[1] - a[1]).map(([m, n]) => ({ model: m, tasks: n })),
237
- byEngine,
238
- engineIndependence,
239
- scm,
240
- rating: { avg, count: ratings.length, recent: recentRatings.length ? recentRatings.reduce((a, b) => a + b, 0) / recentRatings.length : null },
241
- refs,
242
- since: list[0]?.at || null,
243
- last: list.at(-1)?.at || null,
244
- head: list.at(-1)?.hash || null,
245
- };
246
- }
247
-
248
- /**
249
- * How well an agent TYPE fits a job, with that type's record. `job.needs` is
250
- * `{ skills[], tools[], grants[] }`; `type` carries `skills[]`, `tools[]`, `grants[]`; the
251
- * summary is `summarize()`'s. Returns `{ score, reasons }` in [0, 1] — needs first (a type
252
- * without the tools cannot do the job), track record second, size third.
253
- */
254
- export function fit(job, type, summary = null, { qualityOf = null, costOf = null, adjust = true } = {}) {
255
- const needs = job?.needs || {};
256
- const have = (xs) => new Set((xs || []).map((x) => String(x).toLowerCase()));
257
- const skills = have(type?.skills); const tools = have(type?.tools); const grants = have(type?.grants);
258
- const reasons = [];
259
- const coverage = (want, has, label) => {
260
- const w = (want || []).map((x) => String(x).toLowerCase());
261
- if (!w.length) return 1;
262
- const hit = w.filter((x) => has.has(x));
263
- if (hit.length < w.length) reasons.push(`missing ${label}: ${w.filter((x) => !has.has(x)).join(', ')}`);
264
- return hit.length / w.length;
265
- };
266
- const cSkills = coverage(needs.skills, skills, 'skills');
267
- const cTools = coverage(needs.tools, tools, 'tools');
268
- const cGrants = coverage(needs.grants, grants, 'grants');
269
- const needScore = (cSkills * 0.5 + cTools * 0.3 + cGrants * 0.2);
270
- if (needScore === 1) reasons.push('has every skill, tool and grant the job names');
271
- let record = 0.5; // a fresh type is neither trusted nor distrusted
272
- let adjusted = null;
273
- if (summary && summary.entries) {
274
- const doneRate = summary.jobsDone + summary.jobsFailed ? summary.jobsDone / (summary.jobsDone + summary.jobsFailed) : 0.5;
275
- // The track record uses the MODEL-ADJUSTED rating when the caller can say what the
276
- // engines were worth (§13.3): an agent rated 0.82 mostly on a weak engine ranks above
277
- // one rated 0.82 on a frontier model. The reasons say so, and a person can turn it off.
278
- adjusted = adjust && qualityOf && summary.rating.avg != null ? adjustSummary(summary, { qualityOf, costOf: costOf || undefined }) : null;
279
- const rated = summary.rating.avg == null ? 0.5 : (adjusted?.adjusted ?? summary.rating.avg);
280
- record = doneRate * 0.5 + rated * 0.5;
281
- reasons.push(`${summary.jobsDone} done, ${summary.jobsFailed} failed${summary.rating.avg != null ? (adjusted && adjusted.adjusted !== adjusted.raw ? `, rated ${Math.round(adjusted.raw * 100)}% raw, ${Math.round(adjusted.adjusted * 100)}% adjusted — ${adjusted.basis[0] || 'engine-corrected'}` : `, rated ${Math.round(summary.rating.avg * 100)}%`) : ''}`);
282
- if (adjusted?.leverage != null && adjusted.leverage > 0.05) reasons.push(`adds ${adjusted.leverage} over its engines' own quality`);
283
- if (adjusted?.efficiency) reasons.push(`cleared the bar cheapest on ${adjusted.efficiency.engine}`);
284
- if (summary.roles.orchestrator + summary.roles.manager + summary.roles['manager-of-managers'] > 0) reasons.push(`has led: ${summary.roles.orchestrator} as orchestrator, ${summary.roles.manager} as manager`);
285
- } else {
286
- reasons.push('no record yet');
287
- }
288
- const wantSize = Number(job?.size?.steps) || 0;
289
- const sizeScore = !wantSize ? 1 : Math.min(1, (summary?.size?.largestSteps || 0) / wantSize) * 0.5 + 0.5;
290
- if (wantSize && (summary?.size?.largestSteps || 0) < wantSize) reasons.push(`largest task so far ${summary?.size?.largestSteps || 0} steps; this one is ~${wantSize}`);
291
- const score = Math.round((needScore * 0.6 + record * 0.3 + sizeScore * 0.1) * 1000) / 1000;
292
- return { score, reasons, parts: { needs: needScore, record, size: sizeScore }, ...(adjusted ? { adjusted } : {}) };
293
- }
294
-
295
- // ── Agent scores, normalised by engine (§13.3) — what the model ledger's cards make possible ──
296
-
297
- /**
298
- * The model-adjusted view of an agent's card (scorecard.js `summarize()`), given what its
299
- * engines are worth: `qualityOf(key)` → the engine's quality in [0, 1] (the card's mean
300
- * rating for the job kind when observed, else the router's guess) or null when unknown.
301
- *
302
- * leverage rating on an engine minus that engine's quality, weighted by tasks — what
303
- * the agent's prompt and tools add that the model does not supply on its own
304
- * adjusted the raw rating corrected for the engines it ran on: work done on a weak
305
- * engine counts for more, on a strong one for less; `k` bounds the correction
306
- * efficiency adjusted rating ÷ cost per task on the cheapest engine that cleared `bar`
307
- * (`costOf(key)` → $/task or a token proxy; null when nothing is priced)
308
- *
309
- * Returns `{ raw, adjusted, leverage, efficiency, basis[] }` with `basis` the reasons a
310
- * person reads ("60 % of its tasks ran on a 0.3-quality engine").
311
- */
312
- export function adjustSummary(summary, { qualityOf = () => null, costOf = () => null, reference = 0.6, k = 0.3, bar = 0.5 } = {}) {
313
- const raw = summary?.rating?.avg ?? null;
314
- const rows = (summary?.byEngine || []).filter((r) => r.key);
315
- const known = rows.map((r) => ({ ...r, quality: qualityOf(r.key) })).filter((r) => Number.isFinite(r.quality));
316
- const totalTasks = known.reduce((n, r) => n + r.tasks, 0);
317
- const basis = [];
318
- if (raw == null || !known.length || !totalTasks) return { raw, adjusted: raw, leverage: null, efficiency: null, basis: raw == null ? ['not rated yet'] : ['engines not rated yet — raw rating used'] };
319
- // Correction: how far below the reference the engines it ran on sit, task-weighted.
320
- const correction = k * known.reduce((s, r) => s + (r.tasks / totalTasks) * (reference - r.quality), 0);
321
- const adjusted = Math.max(0, Math.min(1, raw + correction));
322
- const weak = known.filter((r) => r.quality < reference);
323
- if (weak.length) basis.push(`${Math.round((weak.reduce((n, r) => n + r.tasks, 0) / totalTasks) * 100)} % of its tasks ran on ${weak.length === 1 ? `a ${weak[0].quality}-quality engine` : 'engines below the reference'}`);
324
- const strong = known.filter((r) => r.quality > reference);
325
- if (strong.length && !weak.length) basis.push(`ran on engines above the reference (${strong.map((r) => r.quality).join(', ')})`);
326
- // Leverage over the engines it was rated on.
327
- const rated = known.filter((r) => r.rating?.avg != null);
328
- const ratedTasks = rated.reduce((n, r) => n + r.rating.count, 0);
329
- const leverage = ratedTasks ? r3(rated.reduce((s, r) => s + (r.rating.count / ratedTasks) * (r.rating.avg - r.quality), 0)) : null;
330
- if (leverage != null) basis.push(`${leverage >= 0 ? '+' : ''}${leverage} over its engines' own quality`);
331
- // Efficiency on the cheapest engine that cleared the bar.
332
- const cleared = rated.filter((r) => r.rating.avg >= bar).map((r) => ({ ...r, cost: costOf(r.key) ?? (r.tokens || null) })).filter((r) => r.cost != null && r.cost > 0).sort((a, b) => a.cost - b.cost);
333
- const efficiency = cleared.length ? { value: r3(adjusted / cleared[0].cost), engine: cleared[0].key, costPerTask: cleared[0].cost } : null;
334
- return { raw: r3(raw), adjusted: r3(adjusted), leverage, efficiency, basis };
335
- }
336
-
1
+ const E=Object.freeze(["task.done","task.failed","rating","created","interaction","role"]),T=Object.freeze(["ic","orchestrator","manager","manager-of-managers"]),H=1,_=Object.freeze(["model","harness"]);function A(e){if(!e)return null;const s=typeof e=="string"?{id:e}:e,t=String(s.id||s.harnessId||s.model||"").trim();if(!t)return null;const r=_.includes(s.kind)?s.kind:s.harnessId?"harness":"model",d=s.model!=null&&String(s.model).trim()&&String(s.model)!==t?String(s.model).trim():void 0;return{kind:r,id:t,...d?{model:d}:{},...s.label&&String(s.label)!==t?{label:String(s.label).slice(0,120)}:{}}}function O(e){const s=A(e);return s?`${s.kind}:${s.id}${s.model?`/${s.model}`:""}`:null}function K(e){if(!e||typeof e!="object")return null;const s=(r,d=200)=>r==null||r===""?void 0:String(r).slice(0,d),t={repo:s(e.repo,300),remote:s(e.remote,300),base:s(e.base,120),branch:s(e.branch,120),head:s(e.head,64),headAfter:s(e.headAfter,64),commits:e.commits!=null?Math.max(0,Math.round(Number(e.commits)||0)):void 0,pr:s(e.pr,300),merged:e.merged===!0?!0:e.merged===!1?!1:void 0,dirty:e.dirty===!0?!0:e.dirty===!1?!1:void 0};for(const r of Object.keys(t))t[r]===void 0&&delete t[r];return Object.keys(t).length?t:null}const N=new TextEncoder,C=e=>[...new Uint8Array(e)].map(s=>s.toString(16).padStart(2,"0")).join("");function q(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(q).join(",")}]`:`{${Object.keys(e).sort().map(s=>e[s]===void 0?null:`${JSON.stringify(s)}:${q(e[s])}`).filter(Boolean).join(",")}}`}async function D(e,{subtle:s=globalThis.crypto?.subtle}={}){if(!s)throw new Error("scorecard: no crypto.subtle — pass one");return C(await s.digest("SHA-256",N.encode(String(e))))}function R(e){const{hash:s,sig:t,...r}=e;return r}async function G(e,s,{now:t=()=>Date.now(),subtle:r}={}){if(!e||typeof e!="object")throw new Error("scorecard: an entry needs a fact");if(!E.includes(e.kind))throw new Error(`scorecard: kind must be one of ${E.join(", ")}`);if(!e.agentId)throw new Error("scorecard: agentId required");const d={v:H,seq:s?s.seq+1:0,agentId:String(e.agentId),kind:e.kind,at:Number(e.at)||t(),...e.projectId?{projectId:String(e.projectId)}:{},...e.jobId?{jobId:String(e.jobId)}:{},...e.runId?{runId:String(e.runId)}:{},...e.taskId?{taskId:String(e.taskId)}:{},...e.model?{model:String(e.model)}:{},...A(e.engine)?{engine:A(e.engine)}:{},...K(e.scm)?{scm:K(e.scm)}:{},...e.size?{size:B(e.size)}:{},...e.roleKind?{roleKind:T.includes(e.roleKind)?e.roleKind:"ic"}:{},...Array.isArray(e.tools)&&e.tools.length?{tools:[...new Set(e.tools.map(String))].sort()}:{},...Array.isArray(e.with)&&e.with.length?{with:[...new Set(e.with.map(String))].sort()}:{},...Array.isArray(e.created)&&e.created.length?{created:[...new Set(e.created.map(String))]}:{},...e.rating?{rating:{by:String(e.rating.by||"person"),score:F(e.rating.score),...e.rating.note?{note:String(e.rating.note).slice(0,500)}:{},...e.rating.about!=null?{about:Number(e.rating.about)}:{}}}:{},...Array.isArray(e.refs)&&e.refs.length?{refs:e.refs.map(String).slice(0,12)}:{},...e.error?{error:String(e.error).slice(0,300)}:{},prev:s?s.hash:null};return d.hash=await D(q(R(d)),{subtle:r}),d}const F=e=>Math.max(0,Math.min(1,Number(e)||0)),v=e=>e==null?null:Math.round(e*1e3)/1e3,B=e=>({ms:Math.max(0,Math.round(Number(e.ms)||0)),steps:Math.max(0,Math.round(Number(e.steps)||0)),tools:Math.max(0,Math.round(Number(e.tools)||0)),findings:Math.max(0,Math.round(Number(e.findings)||0)),tokens:Math.max(0,Math.round(Number(e.tokens)||0))});async function J(e,{subtle:s}={}){let t=null;for(const r of e||[]){if(!r||typeof r!="object")return{ok:!1,at:t?t.seq+1:0,why:"not an entry"};if((t?t.seq+1:0)!==r.seq)return{ok:!1,at:r.seq,why:"seq"};if((t?t.hash:null)!==r.prev)return{ok:!1,at:r.seq,why:"prev"};if(await D(q(R(r)),{subtle:s})!==r.hash)return{ok:!1,at:r.seq,why:"hash"};t=r}return{ok:!0,at:null,length:(e||[]).length}}async function U(e,s,{subtle:t=globalThis.crypto?.subtle}={}){const r=await t.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return{...e,sig:C(await t.sign("HMAC",r,N.encode(e.hash)))}}async function P(e,s,{subtle:t=globalThis.crypto?.subtle}={}){const r=await t.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["verify"]),d=[];for(const h of e||[]){const c=h?.sig?new Uint8Array(h.sig.match(/../g).map(j=>parseInt(j,16))):null;d.push(!!c&&await t.verify("HMAC",r,c,N.encode(h.hash)))}return{ok:d.every(Boolean),attested:d.filter(Boolean).length,of:d.length}}function V(e,{recent:s=5}={}){const t=(e||[]).filter(n=>n&&n.kind),r=t.filter(n=>n.kind==="task.done"),d=t.filter(n=>n.kind==="task.failed"),h=n=>r.reduce((i,g)=>i+(g.size?.[n]||0),0),c=r.reduce((n,i)=>Math.max(n,i.size?.steps||0),0),j=new Set,k=new Set,M=new Set,b={ic:0,orchestrator:0,manager:0,"manager-of-managers":0},u=new Map,p=new Map,w=new Map,$=new Map,y=new Map,f={tasks:0,commits:0,prs:0,merged:0};for(const n of t){for(const i of n.tools||[])j.add(i);for(const i of n.with||[])k.add(i);for(const i of n.created||[])M.add(i);if(n.roleKind&&(n.kind==="task.done"||n.kind==="task.failed"||n.kind==="role")&&(b[n.roleKind]=(b[n.roleKind]||0)+1),n.model&&u.set(n.model,(u.get(n.model)||0)+1),n.kind==="task.done"||n.kind==="task.failed"){const i=O(n.engine);if(i){const g=p.get(i)||{engine:A(n.engine),tasks:0,done:0,failed:0,tokens:0,ratings:[]};g.tasks+=1,g[n.kind==="task.done"?"done":"failed"]+=1,g.tokens+=n.size?.tokens||0,p.set(i,g),w.set(n.seq,i),n.taskId&&$.set(`${n.runId||""}/${n.taskId}`,n.seq),n.runId&&y.set(n.runId,[...y.get(n.runId)||[],n.seq])}n.scm&&(f.tasks+=1,f.commits+=n.scm.commits||0,n.scm.pr&&(f.prs+=1),n.scm.merged&&(f.merged+=1))}}for(const n of t){if(n.kind!=="rating"||!n.rating)continue;const i=n.rating.about!=null?n.rating.about:n.taskId&&$.has(`${n.runId||""}/${n.taskId}`)?$.get(`${n.runId||""}/${n.taskId}`):n.runId&&(y.get(n.runId)||[]).length===1?y.get(n.runId)[0]:null,g=i!=null?w.get(i):null;g&&p.get(g).ratings.push(n.rating.score)}const S=n=>n.length?n.reduce((i,g)=>i+g,0)/n.length:null,a=[...p.values()].sort((n,i)=>i.tasks-n.tasks).map(n=>({key:O(n.engine),...n.engine,tasks:n.tasks,done:n.done,failed:n.failed,failRate:n.tasks?Math.round(n.failed/n.tasks*1e3)/1e3:0,tokens:n.tasks?Math.round(n.tokens/n.tasks):0,rating:{avg:S(n.ratings),count:n.ratings.length}})),m=a.filter(n=>n.rating.avg!=null).map(n=>n.rating.avg),o=m.length>=2?Math.round((1-(Math.max(...m)-Math.min(...m)))*1e3)/1e3:null,l=t.filter(n=>n.kind==="rating"&&n.rating).map(n=>n.rating.score),x=l.length?l.reduce((n,i)=>n+i,0)/l.length:null,I=l.slice(-s),z=[...new Set(t.flatMap(n=>n.refs||[]))].slice(-s);return{agentId:t[0]?.agentId||null,entries:t.length,jobsDone:r.length,jobsFailed:d.length,size:{ms:h("ms"),steps:h("steps"),tools:h("tools"),findings:h("findings"),tokens:h("tokens"),largestSteps:c},tools:[...j].sort(),workedWith:[...k].sort(),created:[...M],roles:b,models:[...u.entries()].sort((n,i)=>i[1]-n[1]).map(([n,i])=>({model:n,tasks:i})),byEngine:a,engineIndependence:o,scm:f,rating:{avg:x,count:l.length,recent:I.length?I.reduce((n,i)=>n+i,0)/I.length:null},refs:z,since:t[0]?.at||null,last:t.at(-1)?.at||null,head:t.at(-1)?.hash||null}}function W(e,s,t=null,{qualityOf:r=null,costOf:d=null,adjust:h=!0}={}){const c=e?.needs||{},j=x=>new Set((x||[]).map(I=>String(I).toLowerCase())),k=j(s?.skills),M=j(s?.tools),b=j(s?.grants),u=[],p=(x,I,z)=>{const n=(x||[]).map(g=>String(g).toLowerCase());if(!n.length)return 1;const i=n.filter(g=>I.has(g));return i.length<n.length&&u.push(`missing ${z}: ${n.filter(g=>!I.has(g)).join(", ")}`),i.length/n.length},w=p(c.skills,k,"skills"),$=p(c.tools,M,"tools"),y=p(c.grants,b,"grants"),f=w*.5+$*.3+y*.2;f===1&&u.push("has every skill, tool and grant the job names");let S=.5,a=null;if(t&&t.entries){const x=t.jobsDone+t.jobsFailed?t.jobsDone/(t.jobsDone+t.jobsFailed):.5;a=h&&r&&t.rating.avg!=null?L(t,{qualityOf:r,costOf:d||void 0}):null;const I=t.rating.avg==null?.5:a?.adjusted??t.rating.avg;S=x*.5+I*.5,u.push(`${t.jobsDone} done, ${t.jobsFailed} failed${t.rating.avg!=null?a&&a.adjusted!==a.raw?`, rated ${Math.round(a.raw*100)}% raw, ${Math.round(a.adjusted*100)}% adjusted — ${a.basis[0]||"engine-corrected"}`:`, rated ${Math.round(t.rating.avg*100)}%`:""}`),a?.leverage!=null&&a.leverage>.05&&u.push(`adds ${a.leverage} over its engines' own quality`),a?.efficiency&&u.push(`cleared the bar cheapest on ${a.efficiency.engine}`),t.roles.orchestrator+t.roles.manager+t.roles["manager-of-managers"]>0&&u.push(`has led: ${t.roles.orchestrator} as orchestrator, ${t.roles.manager} as manager`)}else u.push("no record yet");const m=Number(e?.size?.steps)||0,o=m?Math.min(1,(t?.size?.largestSteps||0)/m)*.5+.5:1;return m&&(t?.size?.largestSteps||0)<m&&u.push(`largest task so far ${t?.size?.largestSteps||0} steps; this one is ~${m}`),{score:Math.round((f*.6+S*.3+o*.1)*1e3)/1e3,reasons:u,parts:{needs:f,record:S,size:o},...a?{adjusted:a}:{}}}function L(e,{qualityOf:s=()=>null,costOf:t=()=>null,reference:r=.6,k:d=.3,bar:h=.5}={}){const c=e?.rating?.avg??null,k=(e?.byEngine||[]).filter(o=>o.key).map(o=>({...o,quality:s(o.key)})).filter(o=>Number.isFinite(o.quality)),M=k.reduce((o,l)=>o+l.tasks,0),b=[];if(c==null||!k.length||!M)return{raw:c,adjusted:c,leverage:null,efficiency:null,basis:c==null?["not rated yet"]:["engines not rated yet — raw rating used"]};const u=d*k.reduce((o,l)=>o+l.tasks/M*(r-l.quality),0),p=Math.max(0,Math.min(1,c+u)),w=k.filter(o=>o.quality<r);w.length&&b.push(`${Math.round(w.reduce((o,l)=>o+l.tasks,0)/M*100)} % of its tasks ran on ${w.length===1?`a ${w[0].quality}-quality engine`:"engines below the reference"}`);const $=k.filter(o=>o.quality>r);$.length&&!w.length&&b.push(`ran on engines above the reference (${$.map(o=>o.quality).join(", ")})`);const y=k.filter(o=>o.rating?.avg!=null),f=y.reduce((o,l)=>o+l.rating.count,0),S=f?v(y.reduce((o,l)=>o+l.rating.count/f*(l.rating.avg-l.quality),0)):null;S!=null&&b.push(`${S>=0?"+":""}${S} over its engines' own quality`);const a=y.filter(o=>o.rating.avg>=h).map(o=>({...o,cost:t(o.key)??(o.tokens||null)})).filter(o=>o.cost!=null&&o.cost>0).sort((o,l)=>o.cost-l.cost),m=a.length?{value:v(p/a[0].cost),engine:a[0].key,costPerTask:a[0].cost}:null;return{raw:v(c),adjusted:v(p),leverage:S,efficiency:m,basis:b}}export{_ as ENGINE_KINDS,T as ROLE_KINDS,E as SCORECARD_ENTRY_KINDS,H as SCORECARD_VERSION,L as adjustSummary,U as attest,q as canonical,O as engineKey,W as fit,G as makeEntry,A as normalizeEngine,K as normalizeScm,D as sha256,V as summarize,P as verifyAttested,J as verifyChain};
@@ -1,134 +1,2 @@
1
- // WARM tier — full-corpus search on the LOCAL gateway.
2
- //
3
- // The gateway is the user's own process, so it may hold decrypted records + the key and
4
- // build a real index outside the browser's memory/CPU (see docs/architecture-data-tiers).
5
- // This is the compute core: a BM25 doc store you can incrementally upsert/remove and
6
- // query. Persistence (encrypted at rest) and the HTTP endpoints layer on top of this.
7
- //
8
- // The tokenizer + BM25 are a VENDORED copy of the extension's meeting-index.js so the
9
- // gateway ranks identically to the browser hot tier — keep them in sync. Pure, no deps.
10
-
11
- const STOP = new Set((
12
- 'the a an and or but of to in on at for with is are was were be been being it this that these those as i you he '
13
- + 'if am because need needs needed its lets let '
14
- + 'she they we us my your our their me him her them so no yes not do does did have has had will would can could '
15
- + 'should from by about into over under again further then once here there all any both each few more most other '
16
- + 'some such only own same than too very just dont cant couldnt didnt doesnt hadnt hasnt havent im ive id isnt '
17
- + 'youre were werent theyre thats theres whats wheres whos wont wouldnt shouldnt okay yeah uh um like really '
18
- + 'going get got know think mean right well say said also one two how what when where which who whom why'
19
- ).split(/\s+/));
20
-
21
- function normalizeToken(raw) {
22
- let word = String(raw || '')
23
- .toLowerCase()
24
- .replace(/[’‘`]/g, "'")
25
- .replace(/[‐‑‒–—]/g, '-')
26
- .replace(/^['+_-]+|['+_-]+$/g, '');
27
- if (word.endsWith("'s")) word = word.slice(0, -2);
28
- const compact = word.replace(/['_-]+/g, '');
29
- if (/^[a-z]\+\+$/.test(word)) return word;
30
- if (compact.length < 2 || /^\d+$/.test(compact)) return '';
31
- if (STOP.has(word) || STOP.has(compact)) return '';
32
- return word.replace(/'/g, '');
33
- }
34
-
35
- export function tokenize(text) {
36
- const m = String(text || '').toLowerCase().match(/[a-z0-9][a-z0-9'_+-]{1,}/g);
37
- if (!m) return [];
38
- return m.map(normalizeToken).filter(Boolean);
39
- }
40
-
41
- // A mutable BM25 index over documents. Each doc: { id, text, title?, type?, date? }.
42
- // upsert/remove are incremental (no full rebuild); search() ranks lazily off the current
43
- // term stats. Deletes are honest removals (the whole point of tombstoned sync upstream).
44
- export class SearchIndex {
45
- constructor() {
46
- this.docs = new Map(); // id -> { tf: Map<term,count>, len, meta }
47
- this.df = new Map(); // term -> #docs containing it
48
- this.totalLen = 0;
49
- }
50
-
51
- get size() { return this.docs.size; }
52
-
53
- _removeStats(prev) {
54
- this.totalLen -= prev.len;
55
- for (const term of prev.tf.keys()) {
56
- const n = (this.df.get(term) || 0) - 1;
57
- if (n <= 0) this.df.delete(term); else this.df.set(term, n);
58
- }
59
- }
60
-
61
- upsert(doc) {
62
- if (!doc || !doc.id) return;
63
- const prev = this.docs.get(doc.id);
64
- if (prev) this._removeStats(prev);
65
- const terms = tokenize(`${doc.title || ''}\n${doc.text || ''}`);
66
- const tf = new Map();
67
- for (const t of terms) tf.set(t, (tf.get(t) || 0) + 1);
68
- for (const t of tf.keys()) this.df.set(t, (this.df.get(t) || 0) + 1);
69
- this.totalLen += terms.length;
70
- this.docs.set(doc.id, {
71
- tf,
72
- len: terms.length,
73
- meta: { id: doc.id, title: doc.title || '', type: doc.type || '', date: doc.date || 0 },
74
- });
75
- }
76
-
77
- remove(id) {
78
- const prev = this.docs.get(id);
79
- if (!prev) return false;
80
- this._removeStats(prev);
81
- this.docs.delete(id);
82
- return true;
83
- }
84
-
85
- bulk({ upserts = [], removes = [] } = {}) {
86
- for (const id of removes) this.remove(id);
87
- for (const d of upserts) this.upsert(d);
88
- return this.size;
89
- }
90
-
91
- // Okapi BM25. Returns [{ id, score, title, type, date }] sorted desc, top `limit`.
92
- search(query, { limit = 10, k1 = 1.5, b = 0.75 } = {}) {
93
- const qterms = [...new Set(tokenize(query))];
94
- if (!qterms.length || !this.docs.size) return [];
95
- const N = this.docs.size;
96
- const avgdl = this.totalLen / N || 1;
97
- const idf = new Map();
98
- for (const t of qterms) {
99
- const n = this.df.get(t) || 0;
100
- idf.set(t, n ? Math.log(1 + (N - n + 0.5) / (n + 0.5)) : 0);
101
- }
102
- const out = [];
103
- for (const [id, d] of this.docs) {
104
- let s = 0;
105
- for (const t of qterms) {
106
- const f = d.tf.get(t);
107
- if (!f) continue;
108
- s += (idf.get(t) || 0) * (f * (k1 + 1)) / (f + k1 * (1 - b + b * (d.len / avgdl)));
109
- }
110
- if (s > 0) out.push({ id, score: s, ...d.meta });
111
- }
112
- out.sort((a, c) => c.score - a.score);
113
- return out.slice(0, Math.max(1, limit));
114
- }
115
-
116
- // Serialize/restore for encrypted-at-rest persistence (next slice). Maps → arrays.
117
- toJSON() {
118
- return {
119
- v: 1,
120
- docs: [...this.docs].map(([id, d]) => ({ id, len: d.len, meta: d.meta, tf: [...d.tf] })),
121
- };
122
- }
123
-
124
- static fromJSON(blob) {
125
- const idx = new SearchIndex();
126
- for (const d of (blob?.docs || [])) {
127
- const tf = new Map(d.tf || []);
128
- idx.docs.set(d.id, { tf, len: d.len || 0, meta: d.meta || { id: d.id } });
129
- idx.totalLen += d.len || 0;
130
- for (const t of tf.keys()) idx.df.set(t, (idx.df.get(t) || 0) + 1);
131
- }
132
- return idx;
133
- }
134
- }
1
+ const w=new Set("the a an and or but of to in on at for with is are was were be been being it this that these those as i you he if am because need needs needed its lets let she they we us my your our their me him her them so no yes not do does did have has had will would can could should from by about into over under again further then once here there all any both each few more most other some such only own same than too very just dont cant couldnt didnt doesnt hadnt hasnt havent im ive id isnt youre were werent theyre thats theres whats wheres whos wont wouldnt shouldnt okay yeah uh um like really going get got know think mean right well say said also one two how what when where which who whom why".split(/\s+/));function y(h){let t=String(h||"").toLowerCase().replace(/[’‘`]/g,"'").replace(/[‐‑‒–—]/g,"-").replace(/^['+_-]+|['+_-]+$/g,"");t.endsWith("'s")&&(t=t.slice(0,-2));const e=t.replace(/['_-]+/g,"");return/^[a-z]\+\+$/.test(t)?t:e.length<2||/^\d+$/.test(e)||w.has(t)||w.has(e)?"":t.replace(/'/g,"")}function m(h){const t=String(h||"").toLowerCase().match(/[a-z0-9][a-z0-9'_+-]{1,}/g);return t?t.map(y).filter(Boolean):[]}class g{constructor(){this.docs=new Map,this.df=new Map,this.totalLen=0}get size(){return this.docs.size}_removeStats(t){this.totalLen-=t.len;for(const e of t.tf.keys()){const s=(this.df.get(e)||0)-1;s<=0?this.df.delete(e):this.df.set(e,s)}}upsert(t){if(!t||!t.id)return;const e=this.docs.get(t.id);e&&this._removeStats(e);const s=m(`${t.title||""}
2
+ ${t.text||""}`),n=new Map;for(const o of s)n.set(o,(n.get(o)||0)+1);for(const o of n.keys())this.df.set(o,(this.df.get(o)||0)+1);this.totalLen+=s.length,this.docs.set(t.id,{tf:n,len:s.length,meta:{id:t.id,title:t.title||"",type:t.type||"",date:t.date||0}})}remove(t){const e=this.docs.get(t);return e?(this._removeStats(e),this.docs.delete(t),!0):!1}bulk({upserts:t=[],removes:e=[]}={}){for(const s of e)this.remove(s);for(const s of t)this.upsert(s);return this.size}search(t,{limit:e=10,k1:s=1.5,b:n=.75}={}){const o=[...new Set(m(t))];if(!o.length||!this.docs.size)return[];const l=this.docs.size,p=this.totalLen/l||1,d=new Map;for(const i of o){const r=this.df.get(i)||0;d.set(i,r?Math.log(1+(l-r+.5)/(r+.5)):0)}const a=[];for(const[i,r]of this.docs){let c=0;for(const u of o){const f=r.tf.get(u);f&&(c+=(d.get(u)||0)*(f*(s+1))/(f+s*(1-n+n*(r.len/p))))}c>0&&a.push({id:i,score:c,...r.meta})}return a.sort((i,r)=>r.score-i.score),a.slice(0,Math.max(1,e))}toJSON(){return{v:1,docs:[...this.docs].map(([t,e])=>({id:t,len:e.len,meta:e.meta,tf:[...e.tf]}))}}static fromJSON(t){const e=new g;for(const s of t?.docs||[]){const n=new Map(s.tf||[]);e.docs.set(s.id,{tf:n,len:s.len||0,meta:s.meta||{id:s.id}}),e.totalLen+=s.len||0;for(const o of n.keys())e.df.set(o,(e.df.get(o)||0)+1)}return e}}export{g as SearchIndex,m as tokenize};