@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.
- package/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2290
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/history-store.js
CHANGED
|
@@ -1,251 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// The SearchIndex keeps only term-frequencies + light meta, so it can rank but
|
|
4
|
-
// can't hand back a full record. This store keeps the raw records so the gateway
|
|
5
|
-
// can (a) survive a restart WITHOUT the extension re-ingesting everything — the
|
|
6
|
-
// user's "no cold start" requirement — and (b) serve read endpoints (list/get)
|
|
7
|
-
// that an external UI renders. The BM25 index is derived from the store and
|
|
8
|
-
// rebuilt on load (cheap, in-memory), so only the store is persisted.
|
|
9
|
-
//
|
|
10
|
-
// ENCRYPTED AT REST: records are AES-256-GCM'd with a key generated once and kept
|
|
11
|
-
// at ~/.chatpanel/history-key (0600). This is the LOCAL/on-device tier — a local
|
|
12
|
-
// key is correct here; zero-knowledge (keys never on the box) is the future CLOUD
|
|
13
|
-
// tier, not this one. The file on disk is useless without the local key.
|
|
14
|
-
|
|
15
|
-
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
16
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync, unlinkSync, statSync } from 'node:fs';
|
|
17
|
-
import { join, dirname } from 'node:path';
|
|
18
|
-
import os from 'node:os';
|
|
19
|
-
import { SearchIndex } from './search-index.js';
|
|
20
|
-
|
|
21
|
-
const DIR = join(os.homedir(), '.chatpanel');
|
|
22
|
-
const STORE_PATH = process.env.CHATPANEL_HISTORY_STORE || join(DIR, 'history-store.enc');
|
|
23
|
-
const KEY_PATH = process.env.CHATPANEL_HISTORY_KEY || join(DIR, 'history-key');
|
|
24
|
-
const SECRET_PATH = process.env.CHATPANEL_HISTORY_SECRET || join(DIR, 'history-secret.enc');
|
|
25
|
-
|
|
26
|
-
function loadOrCreateKey() {
|
|
27
|
-
try {
|
|
28
|
-
if (existsSync(KEY_PATH)) return Buffer.from(readFileSync(KEY_PATH, 'utf8').trim(), 'base64');
|
|
29
|
-
} catch {
|
|
30
|
-
/* regenerate below */
|
|
31
|
-
}
|
|
32
|
-
const key = randomBytes(32);
|
|
33
|
-
mkdirSync(dirname(KEY_PATH), { recursive: true });
|
|
34
|
-
writeFileSync(KEY_PATH, key.toString('base64'), { mode: 0o600 });
|
|
35
|
-
try {
|
|
36
|
-
chmodSync(KEY_PATH, 0o600);
|
|
37
|
-
} catch {
|
|
38
|
-
/* best effort on platforms without POSIX perms */
|
|
39
|
-
}
|
|
40
|
-
return key;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function encrypt(key, plaintextBuf) {
|
|
44
|
-
const iv = randomBytes(12);
|
|
45
|
-
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
46
|
-
const ct = Buffer.concat([cipher.update(plaintextBuf), cipher.final()]);
|
|
47
|
-
return { v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), ct: ct.toString('base64') };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function decrypt(key, env) {
|
|
51
|
-
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(env.iv, 'base64'));
|
|
52
|
-
decipher.setAuthTag(Buffer.from(env.tag, 'base64'));
|
|
53
|
-
return Buffer.concat([decipher.update(Buffer.from(env.ct, 'base64')), decipher.final()]);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// The handed-off backup passphrase, encrypted at rest with the same local key.
|
|
57
|
-
// Kept separate from the records file: it's a credential, not corpus data, and the
|
|
58
|
-
// gateway needs it before the store is even loaded (startup backup-ingest).
|
|
59
|
-
export function saveBackupSecret(passphrase) {
|
|
60
|
-
if (!String(passphrase || '')) return clearBackupSecret();
|
|
61
|
-
const env = encrypt(loadOrCreateKey(), Buffer.from(String(passphrase || ''), 'utf8'));
|
|
62
|
-
mkdirSync(dirname(SECRET_PATH), { recursive: true });
|
|
63
|
-
writeFileSync(SECRET_PATH, JSON.stringify(env), { mode: 0o600 });
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function clearBackupSecret() {
|
|
67
|
-
try { if (existsSync(SECRET_PATH)) unlinkSync(SECRET_PATH); } catch { /* best effort */ }
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function loadBackupSecret() {
|
|
71
|
-
try {
|
|
72
|
-
if (!existsSync(SECRET_PATH)) return '';
|
|
73
|
-
return decrypt(loadOrCreateKey(), JSON.parse(readFileSync(SECRET_PATH, 'utf8'))).toString('utf8');
|
|
74
|
-
} catch {
|
|
75
|
-
return '';
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export function hasBackupSecret() {
|
|
80
|
-
return !!loadBackupSecret();
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// Records-plus-index with lazy, debounced encrypted persistence.
|
|
84
|
-
export class HistoryStore {
|
|
85
|
-
constructor({ storePath = STORE_PATH, persistMs = 2000 } = {}) {
|
|
86
|
-
this.records = new Map(); // id -> { id, text, title, type, date }
|
|
87
|
-
this.index = new SearchIndex();
|
|
88
|
-
this.storePath = storePath;
|
|
89
|
-
this.persistMs = persistMs;
|
|
90
|
-
this._key = null;
|
|
91
|
-
this._timer = null;
|
|
92
|
-
this._dirty = false;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
get size() {
|
|
96
|
-
return this.records.size;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// The timestamp of the freshest record, so a client can tell how current this warm copy
|
|
100
|
-
// is — the difference between "no such meeting" and "not synced yet".
|
|
101
|
-
get newest() {
|
|
102
|
-
let max = 0;
|
|
103
|
-
for (const r of this.records.values()) if ((r.date || 0) > max) max = r.date || 0;
|
|
104
|
-
return max || null;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// On-disk footprint for the storage dashboard: the encrypted store file.
|
|
108
|
-
get bytes() {
|
|
109
|
-
try { return existsSync(this.storePath) ? statSync(this.storePath).size : 0; } catch { return 0; }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
key() {
|
|
113
|
-
if (!this._key) this._key = loadOrCreateKey();
|
|
114
|
-
return this._key;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// Load the encrypted store from disk and rebuild the index. Safe on a missing/
|
|
118
|
-
// corrupt file — starts empty rather than throwing (fail-open for a cache).
|
|
119
|
-
load() {
|
|
120
|
-
try {
|
|
121
|
-
if (!existsSync(this.storePath)) return this;
|
|
122
|
-
const env = JSON.parse(readFileSync(this.storePath, 'utf8'));
|
|
123
|
-
const records = JSON.parse(decrypt(this.key(), env).toString('utf8'));
|
|
124
|
-
this.records = new Map(records.map((r) => [r.id, r]));
|
|
125
|
-
this.index = new SearchIndex();
|
|
126
|
-
for (const r of this.records.values()) this.index.upsert(r);
|
|
127
|
-
} catch {
|
|
128
|
-
this.records = new Map();
|
|
129
|
-
this.index = new SearchIndex();
|
|
130
|
-
}
|
|
131
|
-
return this;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// Write the encrypted store now (synchronous). Callers normally use the
|
|
135
|
-
// debounced schedulePersist(); this is the flush.
|
|
136
|
-
persistNow() {
|
|
137
|
-
this._dirty = false;
|
|
138
|
-
if (this._timer) {
|
|
139
|
-
clearTimeout(this._timer);
|
|
140
|
-
this._timer = null;
|
|
141
|
-
}
|
|
142
|
-
const buf = Buffer.from(JSON.stringify([...this.records.values()]), 'utf8');
|
|
143
|
-
const env = encrypt(this.key(), buf);
|
|
144
|
-
mkdirSync(dirname(this.storePath), { recursive: true });
|
|
145
|
-
writeFileSync(this.storePath, JSON.stringify(env), { mode: 0o600 });
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
schedulePersist() {
|
|
149
|
-
this._dirty = true;
|
|
150
|
-
if (this._timer) return;
|
|
151
|
-
this._timer = setTimeout(() => {
|
|
152
|
-
this._timer = null;
|
|
153
|
-
if (this._dirty) {
|
|
154
|
-
try {
|
|
155
|
-
this.persistNow();
|
|
156
|
-
} catch {
|
|
157
|
-
/* keep serving from memory even if disk write fails */
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}, this.persistMs);
|
|
161
|
-
if (this._timer.unref) this._timer.unref(); // don't hold the process open
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// Apply upserts/removes to BOTH the record store and the index, then schedule a
|
|
165
|
-
// persist. Returns the new size. Mirrors SearchIndex.bulk's shape.
|
|
166
|
-
bulk({ upserts = [], removes = [] } = {}) {
|
|
167
|
-
for (const id of removes) {
|
|
168
|
-
this.records.delete(id);
|
|
169
|
-
this.index.remove(id);
|
|
170
|
-
}
|
|
171
|
-
for (const d of upserts) {
|
|
172
|
-
if (!d || !d.id) continue;
|
|
173
|
-
const rec = { id: d.id, text: String(d.text || ''), title: d.title || '', type: d.type || '', date: d.date || 0 };
|
|
174
|
-
this.records.set(rec.id, rec);
|
|
175
|
-
this.index.upsert(rec);
|
|
176
|
-
}
|
|
177
|
-
this.schedulePersist();
|
|
178
|
-
return this.records.size;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// Wipe every record — the user purging the on-disk warm copy. Returns how many were dropped.
|
|
182
|
-
clear() {
|
|
183
|
-
const n = this.records.size;
|
|
184
|
-
this.records.clear();
|
|
185
|
-
this.index = new SearchIndex();
|
|
186
|
-
this.schedulePersist();
|
|
187
|
-
return n;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// Mirror the SQLite engine's richer contract so both backends behave the same: type/date
|
|
191
|
-
// filters, offset paging, and a matching snippet (over-fetch from the ranker, then filter
|
|
192
|
-
// and page, since SearchIndex has no WHERE clause).
|
|
193
|
-
search(query, { limit = 10, offset = 0, type = null, since = null, before = null } = {}) {
|
|
194
|
-
const raw = this.index.search(query, { limit: (limit + offset) * 3 + 20 });
|
|
195
|
-
const out = [];
|
|
196
|
-
for (const r of raw) {
|
|
197
|
-
const rec = this.records.get(r.id);
|
|
198
|
-
if (!rec) continue;
|
|
199
|
-
if (type && rec.type !== type) continue;
|
|
200
|
-
if (since != null && (rec.date || 0) < since) continue;
|
|
201
|
-
if (before != null && (rec.date || 0) > before) continue;
|
|
202
|
-
out.push({ id: r.id, score: r.score, title: rec.title, type: rec.type, date: rec.date, snippet: snippetOf(rec.text, query) });
|
|
203
|
-
}
|
|
204
|
-
return out.slice(offset, offset + limit);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// Graph navigation — records most connected to this one, by shared content.
|
|
208
|
-
related(id, { limit = 5 } = {}) {
|
|
209
|
-
const rec = this.records.get(id);
|
|
210
|
-
if (!rec) return [];
|
|
211
|
-
const raw = this.index.search(`${rec.title || ''} ${String(rec.text || '').slice(0, 2000)}`, { limit: limit + 5 });
|
|
212
|
-
return raw.filter((r) => r.id !== id).slice(0, limit).map((r) => {
|
|
213
|
-
const m = this.records.get(r.id) || {};
|
|
214
|
-
return { id: r.id, score: r.score, title: m.title, type: m.type, date: m.date };
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// Metadata list for an external UI, newest first, paginated. No bodies.
|
|
219
|
-
list({ limit = 50, offset = 0, type = null } = {}) {
|
|
220
|
-
const all = [...this.records.values()]
|
|
221
|
-
.filter((r) => !type || r.type === type)
|
|
222
|
-
.map((r) => ({ id: r.id, title: r.title, type: r.type, date: r.date, chars: r.text.length }))
|
|
223
|
-
.sort((a, b) => (b.date || 0) - (a.date || 0));
|
|
224
|
-
return { total: all.length, items: all.slice(offset, offset + limit) };
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// Paged fetch for token management (maxChars/offset), matching SqliteHistoryStore.get.
|
|
228
|
-
get(id, { maxChars = null, offset = 0 } = {}) {
|
|
229
|
-
const rec = this.records.get(id);
|
|
230
|
-
if (!rec) return null;
|
|
231
|
-
const full = String(rec.text || '');
|
|
232
|
-
let text = offset ? full.slice(offset) : full;
|
|
233
|
-
let truncated = false;
|
|
234
|
-
if (maxChars && text.length > maxChars) { text = text.slice(0, maxChars); truncated = true; }
|
|
235
|
-
return { ...rec, text, totalChars: full.length, offset: Number(offset) || 0, truncated };
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// A short excerpt of `text` around the first query-term hit — the token-friendly preview a
|
|
240
|
-
// search returns instead of the whole body. Falls back to the head when no term matches.
|
|
241
|
-
function snippetOf(text, query, radius = 90) {
|
|
242
|
-
const s = String(text || '');
|
|
243
|
-
if (!s) return '';
|
|
244
|
-
const terms = String(query || '').toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g) || [];
|
|
245
|
-
const lower = s.toLowerCase();
|
|
246
|
-
let idx = -1;
|
|
247
|
-
for (const t of terms) { const i = lower.indexOf(t); if (i >= 0 && (idx < 0 || i < idx)) idx = i; }
|
|
248
|
-
if (idx < 0) return s.slice(0, radius * 2).replace(/\s+/g, ' ').trim();
|
|
249
|
-
const start = Math.max(0, idx - radius);
|
|
250
|
-
return `${start > 0 ? '… ' : ''}${s.slice(start, idx + radius).replace(/\s+/g, ' ').trim()}${idx + radius < s.length ? ' …' : ''}`;
|
|
251
|
-
}
|
|
1
|
+
import{randomBytes as w,createCipheriv as P,createDecipheriv as O}from"node:crypto";import{readFileSync as y,writeFileSync as g,existsSync as l,mkdirSync as S,chmodSync as B,unlinkSync as N,statSync as b}from"node:fs";import{join as p,dirname as _}from"node:path";import A from"node:os";import{SearchIndex as m}from"./search-index.js";const x=p(A.homedir(),".chatpanel"),E=process.env.CHATPANEL_HISTORY_STORE||p(x,"history-store.enc"),f=process.env.CHATPANEL_HISTORY_KEY||p(x,"history-key"),h=process.env.CHATPANEL_HISTORY_SECRET||p(x,"history-secret.enc");function v(){try{if(l(f))return Buffer.from(y(f,"utf8").trim(),"base64")}catch{}const c=w(32);S(_(f),{recursive:!0}),g(f,c.toString("base64"),{mode:384});try{B(f,384)}catch{}return c}function T(c,r){const e=w(12),t=P("aes-256-gcm",c,e),n=Buffer.concat([t.update(r),t.final()]);return{v:1,iv:e.toString("base64"),tag:t.getAuthTag().toString("base64"),ct:n.toString("base64")}}function k(c,r){const e=O("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return e.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([e.update(Buffer.from(r.ct,"base64")),e.final()])}function Y(c){if(!String(c||""))return H();const r=T(v(),Buffer.from(String(c||""),"utf8"));S(_(h),{recursive:!0}),g(h,JSON.stringify(r),{mode:384})}function H(){try{l(h)&&N(h)}catch{}}function C(){try{return l(h)?k(v(),JSON.parse(y(h,"utf8"))).toString("utf8"):""}catch{return""}}function $(){return!!C()}class K{constructor({storePath:r=E,persistMs:e=2e3}={}){this.records=new Map,this.index=new m,this.storePath=r,this.persistMs=e,this._key=null,this._timer=null,this._dirty=!1}get size(){return this.records.size}get newest(){let r=0;for(const e of this.records.values())(e.date||0)>r&&(r=e.date||0);return r||null}get bytes(){try{return l(this.storePath)?b(this.storePath).size:0}catch{return 0}}key(){return this._key||(this._key=v()),this._key}load(){try{if(!l(this.storePath))return this;const r=JSON.parse(y(this.storePath,"utf8")),e=JSON.parse(k(this.key(),r).toString("utf8"));this.records=new Map(e.map(t=>[t.id,t])),this.index=new m;for(const t of this.records.values())this.index.upsert(t)}catch{this.records=new Map,this.index=new m}return this}persistNow(){this._dirty=!1,this._timer&&(clearTimeout(this._timer),this._timer=null);const r=Buffer.from(JSON.stringify([...this.records.values()]),"utf8"),e=T(this.key(),r);S(_(this.storePath),{recursive:!0}),g(this.storePath,JSON.stringify(e),{mode:384})}schedulePersist(){this._dirty=!0,!this._timer&&(this._timer=setTimeout(()=>{if(this._timer=null,this._dirty)try{this.persistNow()}catch{}},this.persistMs),this._timer.unref&&this._timer.unref())}bulk({upserts:r=[],removes:e=[]}={}){for(const t of e)this.records.delete(t),this.index.remove(t);for(const t of r){if(!t||!t.id)continue;const n={id:t.id,text:String(t.text||""),title:t.title||"",type:t.type||"",date:t.date||0};this.records.set(n.id,n),this.index.upsert(n)}return this.schedulePersist(),this.records.size}clear(){const r=this.records.size;return this.records.clear(),this.index=new m,this.schedulePersist(),r}search(r,{limit:e=10,offset:t=0,type:n=null,since:i=null,before:s=null}={}){const u=this.index.search(r,{limit:(e+t)*3+20}),d=[];for(const a of u){const o=this.records.get(a.id);o&&(n&&o.type!==n||i!=null&&(o.date||0)<i||s!=null&&(o.date||0)>s||d.push({id:a.id,score:a.score,title:o.title,type:o.type,date:o.date,snippet:R(o.text,r)}))}return d.slice(t,t+e)}related(r,{limit:e=5}={}){const t=this.records.get(r);return t?this.index.search(`${t.title||""} ${String(t.text||"").slice(0,2e3)}`,{limit:e+5}).filter(i=>i.id!==r).slice(0,e).map(i=>{const s=this.records.get(i.id)||{};return{id:i.id,score:i.score,title:s.title,type:s.type,date:s.date}}):[]}list({limit:r=50,offset:e=0,type:t=null}={}){const n=[...this.records.values()].filter(i=>!t||i.type===t).map(i=>({id:i.id,title:i.title,type:i.type,date:i.date,chars:i.text.length})).sort((i,s)=>(s.date||0)-(i.date||0));return{total:n.length,items:n.slice(e,e+r)}}get(r,{maxChars:e=null,offset:t=0}={}){const n=this.records.get(r);if(!n)return null;const i=String(n.text||"");let s=t?i.slice(t):i,u=!1;return e&&s.length>e&&(s=s.slice(0,e),u=!0),{...n,text:s,totalChars:i.length,offset:Number(t)||0,truncated:u}}}function R(c,r,e=90){const t=String(c||"");if(!t)return"";const n=String(r||"").toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g)||[],i=t.toLowerCase();let s=-1;for(const d of n){const a=i.indexOf(d);a>=0&&(s<0||a<s)&&(s=a)}if(s<0)return t.slice(0,e*2).replace(/\s+/g," ").trim();const u=Math.max(0,s-e);return`${u>0?"… ":""}${t.slice(u,s+e).replace(/\s+/g," ").trim()}${s+e<t.length?" …":""}`}export{K as HistoryStore,H as clearBackupSecret,$ as hasBackupSecret,C as loadBackupSecret,Y as saveBackupSecret};
|
package/src/job.js
CHANGED
|
@@ -1,150 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
// A job — a posting on a project's board that the pool applies to.
|
|
3
|
-
//
|
|
4
|
-
// The executive posts the first jobs; a recruited agent posts more when the work needs more
|
|
5
|
-
// hands, a skill or a tool it does not have; a person posts one by hand. A job says what it
|
|
6
|
-
// needs (skills, tools, grants), what it may cost (carved from the project's budget), and
|
|
7
|
-
// where the work happens (a repo and a base branch — the bridge gives it a worktree). Agents
|
|
8
|
-
// in the pool APPLY by construction (recruit.js scores every type at once); an evaluator
|
|
9
|
-
// picks; the pick is recruited with a budget and the job becomes a role on a run.
|
|
10
|
-
//
|
|
11
|
-
// A job's status is a machine: open → evaluating → recruited → in-progress → done | failed,
|
|
12
|
-
// with withdrawn from any of the first three. Every move is an event on the project's
|
|
13
|
-
// record (project.js foldProject: `job.posted`, `job.updated`).
|
|
1
|
+
import{validateBudget as k,normalizeBudget as c}from"./budget.js";import{GRANT_RE as g}from"./team.js";const b=/^[a-z][a-z0-9_-]{0,63}$/i,l=Object.freeze(["open","evaluating","recruited","in-progress","done","failed","withdrawn"]),y=Object.freeze({open:["evaluating","recruited","withdrawn"],evaluating:["recruited","open","withdrawn"],recruited:["in-progress","open","withdrawn"],"in-progress":["done","failed","open"],done:[],failed:["open"],withdrawn:["open"]}),u=24,f=64;class m extends Error{constructor(t,n){super(n),this.name="JobError",this.code=t}}const a=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),r=(e,t)=>String(e||"").trim().slice(0,t),p=(e,t,n)=>[...new Set((Array.isArray(e)?e:typeof e=="string"?e.split(/[,\s]+/):[]).map(i=>r(i,t)).filter(Boolean))].slice(0,n);function h(e){const t=[];if(!a(e))return{ok:!1,errors:["job must be an object"]};if(b.test(String(e.id||""))||t.push("id: a short identifier (letters, digits, _ -)"),b.test(String(e.projectId||""))||t.push("projectId: the project this job belongs to"),r(e.title,200)||t.push("title: what the job is"),r(e.brief,8e3)||t.push("brief: what to do, what done looks like"),e.needs!==void 0)if(!a(e.needs))t.push("needs: { skills[], tools[], grants[] }");else{const n=(Array.isArray(e.needs.grants)?e.needs.grants:[]).filter(i=>!g.test(String(i)));n.length&&t.push(`needs.grants: not grantable: ${n.join(", ")}`)}if(e.budget!==void 0){const n=k(e.budget);n.ok||t.push(...n.errors.map(i=>`budget: ${i}`))}return e.status!==void 0&&!l.includes(e.status)&&t.push(`status: one of ${l.join(", ")}`),e.dependsOn!==void 0&&!Array.isArray(e.dependsOn)&&t.push("dependsOn: a list of job ids"),e.workspace!==void 0&&e.workspace!==null&&!a(e.workspace)&&t.push("workspace: { repoId, base, branch? }"),e.deadline!==void 0&&e.deadline!==null&&!Number.isFinite(Number(e.deadline))&&t.push("deadline: a time"),{ok:t.length===0,errors:t}}function w(e){const t=h(e);if(!t.ok)throw new m("INVALID",t.errors.join("; "));return{id:String(e.id),projectId:String(e.projectId),title:r(e.title,200),brief:r(e.brief,8e3),needs:{skills:p(e.needs?.skills,80,u),tools:p(e.needs?.tools,120,u),grants:p(e.needs?.grants,64,u).filter(n=>g.test(n))},...e.budget?{budget:c(e.budget)}:{},size:{steps:Math.max(0,Math.round(Number(e.size?.steps)||0))},status:l.includes(e.status)?e.status:"open",postedBy:r(e.postedBy,80)||"person",postedAt:Number(e.postedAt)||Date.now(),...e.deadline?{deadline:Number(e.deadline)}:{},dependsOn:p(e.dependsOn,64,32).filter(n=>n!==e.id),...e.workspace?{workspace:{repoId:r(e.workspace.repoId,120),base:r(e.workspace.base,120)||"main",...e.workspace.branch?{branch:r(e.workspace.branch,200)}:{},...e.workspace.worktreePath?{worktreePath:r(e.workspace.worktreePath,400)}:{}}}:{},applications:Array.isArray(e.applications)?e.applications.slice(0,f).map(A).filter(Boolean):[],...e.recruited?{recruited:I(e.recruited)}:{},...e.runId?{runId:String(e.runId)}:{},...e.result?{result:{text:r(e.result.text,8e3),by:r(e.result.by,80),at:Number(e.result.at)||Date.now(),...Array.isArray(e.result.refs)?{refs:e.result.refs.slice(0,12)}:{}}}:{},...e.origin&&a(e.origin)?{origin:{...e.origin}}:{}}}function A(e){return!a(e)||!e.agentId?null:{agentId:String(e.agentId),...e.engine?{engine:e.engine}:{},fit:Math.max(0,Math.min(1,Number(e.fit)||0)),reasons:Array.isArray(e.reasons)?e.reasons.map(t=>r(t,200)).slice(0,8):[],pitch:r(e.pitch,600),at:Number(e.at)||Date.now()}}function I(e){return{agentId:String(e.agentId),...e.engine?{engine:e.engine}:{},...e.budget?{budget:c(e.budget)}:{},by:r(e.by,80)||"evaluator",at:Number(e.at)||Date.now(),...e.why?{why:r(e.why,600)}:{}}}function N(e){return Object.freeze(w(e))}function S(e,t){return(y[e]||[]).includes(t)}function x(e,t,n,{cards:i={},now:d=Date.now()}={}){return(t||[]).filter(s=>s&&s.enabled!==!1&&(s.appliesTo||["jobs"]).includes("jobs")).map(s=>{const o=n(e,s,i[s.id]||null);return{agentId:s.id,...o.engine?{engine:o.engine}:{},fit:o.score,reasons:o.reasons,pitch:"",at:d}}).sort((s,o)=>!!o.engine-!!s.engine||o.fit-s.fit).slice(0,f)}function B(e,t){return{id:t?.id||e.id,agent:t?.id,name:t?.name||e.title,prompt:[t?.prompt,`Job: ${e.title}
|
|
14
2
|
|
|
15
|
-
|
|
16
|
-
import { GRANT_RE } from './team.js';
|
|
3
|
+
${e.brief}`].filter(Boolean).join(`
|
|
17
4
|
|
|
18
|
-
|
|
19
|
-
export const JOB_STATUSES = Object.freeze(['open', 'evaluating', 'recruited', 'in-progress', 'done', 'failed', 'withdrawn']);
|
|
20
|
-
const NEXT = Object.freeze({
|
|
21
|
-
open: ['evaluating', 'recruited', 'withdrawn'], evaluating: ['recruited', 'open', 'withdrawn'], recruited: ['in-progress', 'open', 'withdrawn'],
|
|
22
|
-
'in-progress': ['done', 'failed', 'open'], done: [], failed: ['open'], withdrawn: ['open'],
|
|
23
|
-
});
|
|
24
|
-
export const MAX_NEEDS = 24;
|
|
25
|
-
export const MAX_APPLICATIONS = 64;
|
|
26
|
-
|
|
27
|
-
export class JobError extends Error {
|
|
28
|
-
constructor(code, message) { super(message); this.name = 'JobError'; this.code = code; }
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
32
|
-
const clip = (s, n) => String(s || '').trim().slice(0, n);
|
|
33
|
-
const list = (xs, n, max) => [...new Set((Array.isArray(xs) ? xs : typeof xs === 'string' ? xs.split(/[,\s]+/) : []).map((x) => clip(x, n)).filter(Boolean))].slice(0, max);
|
|
34
|
-
|
|
35
|
-
export function validateJob(j) {
|
|
36
|
-
const errors = [];
|
|
37
|
-
if (!isRecord(j)) return { ok: false, errors: ['job must be an object'] };
|
|
38
|
-
if (!JOB_ID_RE.test(String(j.id || ''))) errors.push('id: a short identifier (letters, digits, _ -)');
|
|
39
|
-
if (!JOB_ID_RE.test(String(j.projectId || ''))) errors.push('projectId: the project this job belongs to');
|
|
40
|
-
if (!clip(j.title, 200)) errors.push('title: what the job is');
|
|
41
|
-
if (!clip(j.brief, 8000)) errors.push('brief: what to do, what done looks like');
|
|
42
|
-
if (j.needs !== undefined) {
|
|
43
|
-
if (!isRecord(j.needs)) errors.push('needs: { skills[], tools[], grants[] }');
|
|
44
|
-
else {
|
|
45
|
-
const badGrants = (Array.isArray(j.needs.grants) ? j.needs.grants : []).filter((g) => !GRANT_RE.test(String(g)));
|
|
46
|
-
if (badGrants.length) errors.push(`needs.grants: not grantable: ${badGrants.join(', ')}`);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
if (j.budget !== undefined) { const b = validateBudget(j.budget); if (!b.ok) errors.push(...b.errors.map((e) => `budget: ${e}`)); }
|
|
50
|
-
if (j.status !== undefined && !JOB_STATUSES.includes(j.status)) errors.push(`status: one of ${JOB_STATUSES.join(', ')}`);
|
|
51
|
-
if (j.dependsOn !== undefined && !Array.isArray(j.dependsOn)) errors.push('dependsOn: a list of job ids');
|
|
52
|
-
if (j.workspace !== undefined && j.workspace !== null && !isRecord(j.workspace)) errors.push('workspace: { repoId, base, branch? }');
|
|
53
|
-
if (j.deadline !== undefined && j.deadline !== null && !Number.isFinite(Number(j.deadline))) errors.push('deadline: a time');
|
|
54
|
-
return { ok: errors.length === 0, errors };
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export function normalizeJob(j) {
|
|
58
|
-
const v = validateJob(j);
|
|
59
|
-
if (!v.ok) throw new JobError('INVALID', v.errors.join('; '));
|
|
60
|
-
return {
|
|
61
|
-
id: String(j.id),
|
|
62
|
-
projectId: String(j.projectId),
|
|
63
|
-
title: clip(j.title, 200),
|
|
64
|
-
brief: clip(j.brief, 8000),
|
|
65
|
-
needs: {
|
|
66
|
-
skills: list(j.needs?.skills, 80, MAX_NEEDS),
|
|
67
|
-
tools: list(j.needs?.tools, 120, MAX_NEEDS),
|
|
68
|
-
grants: list(j.needs?.grants, 64, MAX_NEEDS).filter((g) => GRANT_RE.test(g)),
|
|
69
|
-
},
|
|
70
|
-
...(j.budget ? { budget: normalizeBudget(j.budget) } : {}),
|
|
71
|
-
size: { steps: Math.max(0, Math.round(Number(j.size?.steps) || 0)) },
|
|
72
|
-
status: JOB_STATUSES.includes(j.status) ? j.status : 'open',
|
|
73
|
-
postedBy: clip(j.postedBy, 80) || 'person',
|
|
74
|
-
postedAt: Number(j.postedAt) || Date.now(),
|
|
75
|
-
...(j.deadline ? { deadline: Number(j.deadline) } : {}),
|
|
76
|
-
dependsOn: list(j.dependsOn, 64, 32).filter((d) => d !== j.id),
|
|
77
|
-
...(j.workspace ? { workspace: { repoId: clip(j.workspace.repoId, 120), base: clip(j.workspace.base, 120) || 'main', ...(j.workspace.branch ? { branch: clip(j.workspace.branch, 200) } : {}), ...(j.workspace.worktreePath ? { worktreePath: clip(j.workspace.worktreePath, 400) } : {}) } } : {}),
|
|
78
|
-
applications: Array.isArray(j.applications) ? j.applications.slice(0, MAX_APPLICATIONS).map(normalizeApplication).filter(Boolean) : [],
|
|
79
|
-
...(j.recruited ? { recruited: normalizeRecruit(j.recruited) } : {}),
|
|
80
|
-
...(j.runId ? { runId: String(j.runId) } : {}),
|
|
81
|
-
...(j.result ? { result: { text: clip(j.result.text, 8000), by: clip(j.result.by, 80), at: Number(j.result.at) || Date.now(), ...(Array.isArray(j.result.refs) ? { refs: j.result.refs.slice(0, 12) } : {}) } } : {}),
|
|
82
|
-
...(j.origin && isRecord(j.origin) ? { origin: { ...j.origin } } : {}),
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function normalizeApplication(a) {
|
|
87
|
-
if (!isRecord(a) || !a.agentId) return null;
|
|
88
|
-
return { agentId: String(a.agentId), ...(a.engine ? { engine: a.engine } : {}), fit: Math.max(0, Math.min(1, Number(a.fit) || 0)), reasons: Array.isArray(a.reasons) ? a.reasons.map((r) => clip(r, 200)).slice(0, 8) : [], pitch: clip(a.pitch, 600), at: Number(a.at) || Date.now() };
|
|
89
|
-
}
|
|
90
|
-
function normalizeRecruit(r) {
|
|
91
|
-
return { agentId: String(r.agentId), ...(r.engine ? { engine: r.engine } : {}), ...(r.budget ? { budget: normalizeBudget(r.budget) } : {}), by: clip(r.by, 80) || 'evaluator', at: Number(r.at) || Date.now(), ...(r.why ? { why: clip(r.why, 600) } : {}) };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export function defineJob(j) { return Object.freeze(normalizeJob(j)); }
|
|
95
|
-
|
|
96
|
-
/** May the job move from `from` to `to`? */
|
|
97
|
-
export function canTransition(from, to) { return (NEXT[from] || []).includes(to); }
|
|
98
|
-
|
|
99
|
-
/** Applications are computed, not asked for: every eligible type in the pool applies at once. */
|
|
100
|
-
export function applyAll(job, pool, fitFn, { cards = {}, now = Date.now() } = {}) {
|
|
101
|
-
// A fit function may also say which ENGINE the agent would run on (recruit.js does); an
|
|
102
|
-
// application without one is not recruitable right now and sorts after those that are.
|
|
103
|
-
return (pool || [])
|
|
104
|
-
.filter((a) => a && a.enabled !== false && (a.appliesTo || ['jobs']).includes('jobs'))
|
|
105
|
-
.map((a) => { const f = fitFn(job, a, cards[a.id] || null); return { agentId: a.id, ...(f.engine ? { engine: f.engine } : {}), fit: f.score, reasons: f.reasons, pitch: '', at: now }; })
|
|
106
|
-
.sort((x, y) => (!!y.engine - !!x.engine) || (y.fit - x.fit))
|
|
107
|
-
.slice(0, MAX_APPLICATIONS);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** A recruited job as the role a run gives the agent: the brief is the prompt, the needs are the grants. */
|
|
111
|
-
export function jobToRole(job, agent) {
|
|
112
|
-
return {
|
|
113
|
-
id: agent?.id || job.id,
|
|
114
|
-
agent: agent?.id,
|
|
115
|
-
name: agent?.name || job.title,
|
|
116
|
-
prompt: [agent?.prompt, `Job: ${job.title}\n\n${job.brief}`].filter(Boolean).join('\n\n'),
|
|
117
|
-
grants: (job.needs?.grants?.length ? job.needs.grants : agent?.grants) || ['none'],
|
|
118
|
-
...(job.dependsOn?.length ? { dependsOn: job.dependsOn } : {}),
|
|
119
|
-
...(job.workspace ? { workspace: job.workspace } : {}),
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/** The jobs that may run now: every dependency done, and not already taken. */
|
|
124
|
-
export function readyJobs(jobs) {
|
|
125
|
-
const byId = new Map((jobs || []).map((j) => [j.id, j]));
|
|
126
|
-
return (jobs || []).filter((j) => j.status === 'open' && (j.dependsOn || []).every((d) => byId.get(d)?.status === 'done'));
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** A blank posting for the form. */
|
|
130
|
-
export function blankJob(projectId = '') {
|
|
131
|
-
return { id: '', projectId, title: '', brief: '', needs: { skills: [], tools: [], grants: [] }, budget: { tokens: 40000, ms: 900000 }, status: 'open', dependsOn: [] };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
export function jobFromForm(form) {
|
|
135
|
-
const budget = {};
|
|
136
|
-
for (const k of ['tokens', 'calls', 'ms', 'usd']) {
|
|
137
|
-
const v = Number(form?.budget?.[k]);
|
|
138
|
-
if (form?.budget?.[k] !== '' && form?.budget?.[k] != null && Number.isFinite(v) && v > 0) budget[k] = v;
|
|
139
|
-
}
|
|
140
|
-
const j = {
|
|
141
|
-
id: String(form?.id || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[^a-z]+/, '').replace(/-+$/, '').slice(0, 64),
|
|
142
|
-
projectId: form?.projectId, title: form?.title, brief: form?.brief,
|
|
143
|
-
needs: { skills: form?.needs?.skills, tools: form?.needs?.tools, grants: form?.needs?.grants },
|
|
144
|
-
...(Object.keys(budget).length ? { budget } : {}),
|
|
145
|
-
status: form?.status || 'open', postedBy: form?.postedBy || 'person', dependsOn: form?.dependsOn,
|
|
146
|
-
...(form?.workspace?.repoId ? { workspace: form.workspace } : {}), ...(form?.size ? { size: form.size } : {}),
|
|
147
|
-
};
|
|
148
|
-
const v = validateJob(j);
|
|
149
|
-
return v.ok ? { ok: true, job: normalizeJob(j) } : { ok: false, errors: v.errors };
|
|
150
|
-
}
|
|
5
|
+
`),grants:(e.needs?.grants?.length?e.needs.grants:t?.grants)||["none"],...e.dependsOn?.length?{dependsOn:e.dependsOn}:{},...e.workspace?{workspace:e.workspace}:{}}}function J(e){const t=new Map((e||[]).map(n=>[n.id,n]));return(e||[]).filter(n=>n.status==="open"&&(n.dependsOn||[]).every(i=>t.get(i)?.status==="done"))}function E(e=""){return{id:"",projectId:e,title:"",brief:"",needs:{skills:[],tools:[],grants:[]},budget:{tokens:4e4,ms:9e5},status:"open",dependsOn:[]}}function _(e){const t={};for(const d of["tokens","calls","ms","usd"]){const s=Number(e?.budget?.[d]);e?.budget?.[d]!==""&&e?.budget?.[d]!=null&&Number.isFinite(s)&&s>0&&(t[d]=s)}const n={id:String(e?.id||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64),projectId:e?.projectId,title:e?.title,brief:e?.brief,needs:{skills:e?.needs?.skills,tools:e?.needs?.tools,grants:e?.needs?.grants},...Object.keys(t).length?{budget:t}:{},status:e?.status||"open",postedBy:e?.postedBy||"person",dependsOn:e?.dependsOn,...e?.workspace?.repoId?{workspace:e.workspace}:{},...e?.size?{size:e.size}:{}},i=h(n);return i.ok?{ok:!0,job:w(n)}:{ok:!1,errors:i.errors}}export{b as JOB_ID_RE,l as JOB_STATUSES,m as JobError,f as MAX_APPLICATIONS,u as MAX_NEEDS,x as applyAll,E as blankJob,S as canTransition,N as defineJob,_ as jobFromForm,B as jobToRole,w as normalizeJob,J as readyJobs,h as validateJob};
|
package/src/knowledge.js
CHANGED
|
@@ -1,215 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
// Everything else ChatPanel stores is a record of an event: a chat happened, a call
|
|
5
|
-
// happened, a human wrote a note. Nothing is a synthesis, so every answer is re-derived
|
|
6
|
-
// from scratch, every session, forever — and a multi-agent run's findings die with the run.
|
|
7
|
-
// A brief is the thing that compounds.
|
|
8
|
-
//
|
|
9
|
-
// FOUR INVARIANTS, and they are the whole defence (see docs/knowledge-compounding.md §5.1):
|
|
10
|
-
//
|
|
11
|
-
// I-K1 Every claim cites raw. A claim with no ref is a BUG, not a weak claim — it is
|
|
12
|
-
// refused on write. Derived text can then always be checked against, or rebuilt
|
|
13
|
-
// from, the immutable records under it.
|
|
14
|
-
// I-K2 A brief is REBUILDABLE. Delete every brief and this module reconstructs them from
|
|
15
|
-
// the record store. That makes a brief a projection — the same guarantee replay()
|
|
16
|
-
// gives the event log — and it makes "rebuild all" a cache clear, not data loss.
|
|
17
|
-
// I-K3 Nothing self-promotes. `draft` is free; `promoted` needs a gate. Class-R
|
|
18
|
-
// derivations may auto-promote (a backlink is not an opinion); model-written prose
|
|
19
|
-
// may not. Unreviewed agent writing compounding into confident nonsense is the
|
|
20
|
-
// failure mode that is undetectable six months later.
|
|
21
|
-
// I-K4 Bounded, or it is a second corpus. A brief has a size ceiling and the SET of
|
|
22
|
-
// briefs has a count ceiling driven by evidence — memory.js already made this
|
|
23
|
-
// argument for memory, and the same sentence applies here.
|
|
24
|
-
//
|
|
25
|
-
// This phase (W1) is entirely class R: no model, no network, no clock of its own. Every
|
|
26
|
-
// claim is something the corpus already states — who was present, when, what co-occurs,
|
|
27
|
-
// what the user themselves told us. Prose synthesis arrives in W3, behind the gate, and
|
|
28
|
-
// lands as `proposed` beside these rather than replacing them.
|
|
29
|
-
//
|
|
30
|
-
// WHY THIS FILE IS THE MODEL AND `knowledge-derive.js` IS THE PASS. Reading a brief and
|
|
31
|
-
// BUILDING one have very different costs: reading needs the shape and the renderer, while
|
|
32
|
-
// building walks the whole corpus and needs entity resolution and the maintenance passes.
|
|
33
|
-
// The MV3 service worker only ever reads — it syncs stored briefs to the gateway — so
|
|
34
|
-
// putting both halves in one module would have put 60 KB of derivation on its cold start
|
|
35
|
-
// for code it never runs. The split is what keeps that honest rather than remembered.
|
|
36
|
-
|
|
37
|
-
// From subject-name.js, not entity.js: this module is on the MV3 service worker's graph and
|
|
38
|
-
// needs exactly one string function, where entity.js also carries alias resolution and merge
|
|
39
|
-
// suggestion. Same argument as the knowledge/knowledge-derive split, one level down.
|
|
40
|
-
import { normalizeSubject } from './subject-name.js';
|
|
41
|
-
|
|
42
|
-
/** draft → proposed → promoted → archived. `promotion.js` (W3) owns the transitions. */
|
|
43
|
-
export const BRIEF_STATES = Object.freeze(['draft', 'proposed', 'promoted', 'archived']);
|
|
44
|
-
|
|
45
|
-
/** What a claim is derived FROM. Class R throughout this phase. */
|
|
46
|
-
export const CLAIM_KINDS = Object.freeze(['presence', 'timeline', 'together', 'wanted', 'stated']);
|
|
47
|
-
|
|
48
|
-
// I-K4, made concrete. A brief that grows without bound is a document, and a document
|
|
49
|
-
// needs its own summary, and then nothing has been gained.
|
|
50
|
-
export const MAX_CLAIMS = 12;
|
|
51
|
-
export const MAX_CLAIM_REFS = 8;
|
|
52
|
-
export const MAX_BRIEF_RECORDS = 200;
|
|
53
|
-
export const MAX_BRIEF_CHARS = 4000;
|
|
54
|
-
|
|
55
|
-
// How many co-occurring subjects a `together` claim names. Past a handful it stops being a
|
|
56
|
-
// statement and becomes a tag cloud.
|
|
57
|
-
const TOGETHER_LIMIT = 5;
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* A stable, non-cryptographic content hash, computed SYNCHRONOUSLY.
|
|
61
|
-
*
|
|
62
|
-
* Deliberately not SHA-256, which `store.js` uses and which is async: derivation walks
|
|
63
|
-
* every record in the corpus and runs in an MV3 service worker, so a hash per record has to
|
|
64
|
-
* be synchronous or the whole pass becomes a promise storm. The job here is DRIFT
|
|
65
|
-
* DETECTION — "has the record this claim cites changed since the claim was made" — not
|
|
66
|
-
* tamper resistance, and FNV-1a answers that exactly as well while staying pure.
|
|
67
|
-
*/
|
|
68
|
-
export function contentHash(text) {
|
|
69
|
-
const s = String(text ?? '');
|
|
70
|
-
let h1 = 0x811c9dc5, h2 = 0x01000193;
|
|
71
|
-
for (let i = 0; i < s.length; i += 1) {
|
|
72
|
-
const c = s.charCodeAt(i);
|
|
73
|
-
h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
|
|
74
|
-
h2 = Math.imul(h2 ^ (c + i), 0x85ebca6b) >>> 0;
|
|
75
|
-
}
|
|
76
|
-
return `f${h1.toString(16).padStart(8, '0')}${h2.toString(16).padStart(8, '0')}`;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** `person:alex rivera` → `brief:person-alex-rivera`. Safe as a storage key and a URL hash. */
|
|
80
|
-
export function briefId(subjectKey) {
|
|
81
|
-
const [kind, ...rest] = String(subjectKey || '').split(':');
|
|
82
|
-
const slug = normalizeSubject(rest.join(':')).replace(/\s+/g, '-').replace(/-+/g, '-');
|
|
83
|
-
if (!kind || !slug) return '';
|
|
84
|
-
// The slug is TRUNCATED, so two long subjects can share one, and it is lossy, so two
|
|
85
|
-
// kinds can too. A hash of the CANONICAL key rides along to separate them. Canonical, not
|
|
86
|
-
// raw: "Alex Rivera" and "alex rivera" are one subject and must land on one id, or a
|
|
87
|
-
// rebuild would fork the page in two — the exact failure I-K2 exists to make impossible.
|
|
88
|
-
const canonical = `${kind}:${normalizeSubject(rest.join(':'))}`;
|
|
89
|
-
return `brief:${kind}-${slug.slice(0, 48)}-${contentHash(canonical).slice(1, 7)}`;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Records are addressed `chat:x` / `meeting:y` / `note:z` — the ref kind is the prefix. */
|
|
93
|
-
function refForRecord(rec) {
|
|
94
|
-
const [kind, ...rest] = String(rec.id).split(':');
|
|
95
|
-
const id = rest.join(':') || rec.id;
|
|
96
|
-
const known = kind === 'chat' || kind === 'meeting' || kind === 'note' || kind === 'page';
|
|
97
|
-
return makeRef({ kind: known ? kind : 'result', id: known ? id : rec.id, hash: contentHash(rec.text) });
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function claim({ id, kind, text, refs, at = 0, confidence = 1 }) {
|
|
101
|
-
return {
|
|
102
|
-
id,
|
|
103
|
-
kind,
|
|
104
|
-
text,
|
|
105
|
-
// I-K1 lives here: a claim is CONSTRUCTED with its refs, and `checkKnowledgeInvariants`
|
|
106
|
-
// refuses one that arrives without them. There is no path that writes a claim first and
|
|
107
|
-
// attaches provenance later, because that path is how provenance goes missing.
|
|
108
|
-
refs: refs.slice(0, MAX_CLAIM_REFS),
|
|
109
|
-
firstSeen: at,
|
|
110
|
-
lastConfirmed: at,
|
|
111
|
-
confidence,
|
|
112
|
-
cls: 'R', // class R — derived, not written. W3's prose claims carry 'C'.
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
117
|
-
const isoDay = (ms) => (ms ? new Date(ms).toISOString().slice(0, 10) : '');
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* The searchable body. A brief is a SOURCE, ranked by the same engine as everything else
|
|
121
|
-
* (design §7.6 — no second retrieval stack), so it has to render to text like one.
|
|
122
|
-
*/
|
|
123
|
-
export function briefToText(brief) {
|
|
124
|
-
if (!brief) return '';
|
|
125
|
-
const L = [`BRIEF: ${brief.subject.name}`];
|
|
126
|
-
if (brief.subject.aliases?.length) L.push(`Also known as: ${brief.subject.aliases.join(', ')}`);
|
|
127
|
-
L.push(`Kind: ${brief.kind}`);
|
|
128
|
-
L.push('');
|
|
129
|
-
for (const c of brief.claims) {
|
|
130
|
-
L.push(`- ${c.text}`);
|
|
131
|
-
if (c.refs.length) L.push(` (${c.refs.map((r) => `${r.kind}:${r.id}`).join(', ')})`);
|
|
132
|
-
}
|
|
133
|
-
if (brief.records.length) {
|
|
134
|
-
L.push('', 'RECORDS:');
|
|
135
|
-
for (const r of brief.records.slice(-40).reverse()) L.push(`- ${r.type}: ${r.title || 'untitled'}`);
|
|
136
|
-
}
|
|
137
|
-
return L.join('\n').slice(0, MAX_BRIEF_CHARS);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* The inverse of `briefToText` — a brief's claims and refs read back out of the text form.
|
|
142
|
-
*
|
|
143
|
-
* Exists because the warm store holds RECORDS: `{ id, title, type, date, text }`, nothing
|
|
144
|
-
* else. Briefs cross to the gateway as that shape, so an agent asking `get_brief` over MCP
|
|
145
|
-
* can only be handed structure if the text form is stable enough to parse. It is: this
|
|
146
|
-
* module writes both ends, and the claim line (`- text`) followed by its refs
|
|
147
|
-
* (` (kind:id, kind:id)`) is a grammar, not a rendering. Round-trips in the tests.
|
|
148
|
-
*
|
|
149
|
-
* Returns `null` for text that is not a brief, so a caller can tell "not a brief" from
|
|
150
|
-
* "a brief with no claims".
|
|
151
|
-
*/
|
|
152
|
-
export function parseBriefText(text) {
|
|
153
|
-
const lines = String(text ?? '').split('\n');
|
|
154
|
-
if (!/^BRIEF: /.test(lines[0] || '')) return null;
|
|
155
|
-
const out = { name: lines[0].slice('BRIEF: '.length).trim(), aliases: [], kind: '', claims: [], records: [] };
|
|
156
|
-
let section = 'head';
|
|
157
|
-
for (let i = 1; i < lines.length; i += 1) {
|
|
158
|
-
const line = lines[i];
|
|
159
|
-
if (section === 'head') {
|
|
160
|
-
if (line.startsWith('Also known as: ')) out.aliases = line.slice(15).split(',').map((a) => a.trim()).filter(Boolean);
|
|
161
|
-
else if (line.startsWith('Kind: ')) out.kind = line.slice(6).trim();
|
|
162
|
-
else if (line === '') section = 'claims';
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
if (line === 'RECORDS:') { section = 'records'; continue; }
|
|
166
|
-
if (section === 'claims' && line.startsWith('- ')) {
|
|
167
|
-
const claim = { text: line.slice(2), refs: [] };
|
|
168
|
-
const next = lines[i + 1] || '';
|
|
169
|
-
const m = /^ \((.*)\)$/.exec(next);
|
|
170
|
-
if (m) {
|
|
171
|
-
claim.refs = m[1].split(', ').map((r) => {
|
|
172
|
-
const idx = r.indexOf(':');
|
|
173
|
-
return idx > 0 ? { kind: r.slice(0, idx), id: r.slice(idx + 1) } : null;
|
|
174
|
-
}).filter(Boolean);
|
|
175
|
-
i += 1;
|
|
176
|
-
}
|
|
177
|
-
out.claims.push(claim);
|
|
178
|
-
} else if (section === 'records' && line.startsWith('- ')) {
|
|
179
|
-
const idx = line.indexOf(': ');
|
|
180
|
-
out.records.push(idx > 0 ? { type: line.slice(2, idx), title: line.slice(idx + 2) } : { type: '', title: line.slice(2) });
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
return out;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** Terms the graph and the search index rank a brief by — its subject and its neighbours. */
|
|
187
|
-
export function briefTerms(brief) {
|
|
188
|
-
if (!brief) return [];
|
|
189
|
-
const together = brief.claims.find((c) => c.kind === 'together');
|
|
190
|
-
const names = together ? together.text.replace(/^Usually alongside /, '').replace(/\.$/, '').split(', ') : [];
|
|
191
|
-
return [...new Set([brief.subject.name, ...(brief.subject.aliases || []), ...names])].filter(Boolean);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* The invariants, as a check rather than a promise. Returns the failures; empty means clean.
|
|
196
|
-
* Same shape as `invariants.js checkInvariants()`, for the same reason: an invariant nobody
|
|
197
|
-
* can run is a comment.
|
|
198
|
-
*/
|
|
199
|
-
export function checkKnowledgeInvariants(brief) {
|
|
200
|
-
const fail = [];
|
|
201
|
-
if (!brief || typeof brief !== 'object') return [{ invariant: 'I-K1', detail: 'not a brief' }];
|
|
202
|
-
if (!BRIEF_STATES.includes(brief.state)) fail.push({ invariant: 'I-K3', detail: `unknown state ${brief.state}` });
|
|
203
|
-
if (brief.state === 'promoted' && brief.cls === 'C') {
|
|
204
|
-
fail.push({ invariant: 'I-K3', detail: 'model-written prose cannot be promoted without the gate' });
|
|
205
|
-
}
|
|
206
|
-
for (const c of brief.claims || []) {
|
|
207
|
-
if (!c.refs?.length) fail.push({ invariant: 'I-K1', detail: `claim ${c.id} cites nothing` });
|
|
208
|
-
if (!CLAIM_KINDS.includes(c.kind) && c.cls !== 'C') {
|
|
209
|
-
fail.push({ invariant: 'I-K1', detail: `claim ${c.id} has unknown kind ${c.kind}` });
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
if ((brief.claims || []).length > MAX_CLAIMS) fail.push({ invariant: 'I-K4', detail: `${brief.claims.length} claims exceeds ${MAX_CLAIMS}` });
|
|
213
|
-
if (briefToText(brief).length >= MAX_BRIEF_CHARS) fail.push({ invariant: 'I-K4', detail: 'brief text is at the ceiling' });
|
|
214
|
-
return fail;
|
|
215
|
-
}
|
|
1
|
+
import{normalizeSubject as d}from"./subject-name.js";const m=Object.freeze(["draft","proposed","promoted","archived"]),g=Object.freeze(["presence","timeline","together","wanted","stated"]),u=12,x=8,S=200,p=4e3,k=5;function h(t){const e=String(t??"");let n=2166136261,i=16777619;for(let s=0;s<e.length;s+=1){const o=e.charCodeAt(s);n=Math.imul(n^o,16777619)>>>0,i=Math.imul(i^o+s,2246822507)>>>0}return`f${n.toString(16).padStart(8,"0")}${i.toString(16).padStart(8,"0")}`}function R(t){const[e,...n]=String(t||"").split(":"),i=d(n.join(":")).replace(/\s+/g,"-").replace(/-+/g,"-");if(!e||!i)return"";const s=`${e}:${d(n.join(":"))}`;return`brief:${e}-${i.slice(0,48)}-${h(s).slice(1,7)}`}function j(t){const[e,...n]=String(t.id).split(":"),i=n.join(":")||t.id,s=e==="chat"||e==="meeting"||e==="note"||e==="page";return makeRef({kind:s?e:"result",id:s?i:t.id,hash:h(t.text)})}function E({id:t,kind:e,text:n,refs:i,at:s=0,confidence:o=1}){return{id:t,kind:e,text:n,refs:i.slice(0,x),firstSeen:s,lastConfirmed:s,confidence:o,cls:"R"}}const A=(t,e,n=`${e}s`)=>`${t} ${t===1?e:n}`,w=t=>t?new Date(t).toISOString().slice(0,10):"";function $(t){if(!t)return"";const e=[`BRIEF: ${t.subject.name}`];t.subject.aliases?.length&&e.push(`Also known as: ${t.subject.aliases.join(", ")}`),e.push(`Kind: ${t.kind}`),e.push("");for(const n of t.claims)e.push(`- ${n.text}`),n.refs.length&&e.push(` (${n.refs.map(i=>`${i.kind}:${i.id}`).join(", ")})`);if(t.records.length){e.push("","RECORDS:");for(const n of t.records.slice(-40).reverse())e.push(`- ${n.type}: ${n.title||"untitled"}`)}return e.join(`
|
|
2
|
+
`).slice(0,p)}function C(t){const e=String(t??"").split(`
|
|
3
|
+
`);if(!/^BRIEF: /.test(e[0]||""))return null;const n={name:e[0].slice(7).trim(),aliases:[],kind:"",claims:[],records:[]};let i="head";for(let s=1;s<e.length;s+=1){const o=e[s];if(i==="head"){o.startsWith("Also known as: ")?n.aliases=o.slice(15).split(",").map(c=>c.trim()).filter(Boolean):o.startsWith("Kind: ")?n.kind=o.slice(6).trim():o===""&&(i="claims");continue}if(o==="RECORDS:"){i="records";continue}if(i==="claims"&&o.startsWith("- ")){const c={text:o.slice(2),refs:[]},f=e[s+1]||"",a=/^ \((.*)\)$/.exec(f);a&&(c.refs=a[1].split(", ").map(l=>{const r=l.indexOf(":");return r>0?{kind:l.slice(0,r),id:l.slice(r+1)}:null}).filter(Boolean),s+=1),n.claims.push(c)}else if(i==="records"&&o.startsWith("- ")){const c=o.indexOf(": ");n.records.push(c>0?{type:o.slice(2,c),title:o.slice(c+2)}:{type:"",title:o.slice(2)})}}return n}function K(t){if(!t)return[];const e=t.claims.find(i=>i.kind==="together"),n=e?e.text.replace(/^Usually alongside /,"").replace(/\.$/,"").split(", "):[];return[...new Set([t.subject.name,...t.subject.aliases||[],...n])].filter(Boolean)}function v(t){const e=[];if(!t||typeof t!="object")return[{invariant:"I-K1",detail:"not a brief"}];m.includes(t.state)||e.push({invariant:"I-K3",detail:`unknown state ${t.state}`}),t.state==="promoted"&&t.cls==="C"&&e.push({invariant:"I-K3",detail:"model-written prose cannot be promoted without the gate"});for(const n of t.claims||[])n.refs?.length||e.push({invariant:"I-K1",detail:`claim ${n.id} cites nothing`}),!g.includes(n.kind)&&n.cls!=="C"&&e.push({invariant:"I-K1",detail:`claim ${n.id} has unknown kind ${n.kind}`});return(t.claims||[]).length>u&&e.push({invariant:"I-K4",detail:`${t.claims.length} claims exceeds ${u}`}),$(t).length>=p&&e.push({invariant:"I-K4",detail:"brief text is at the ceiling"}),e}export{m as BRIEF_STATES,g as CLAIM_KINDS,p as MAX_BRIEF_CHARS,S as MAX_BRIEF_RECORDS,u as MAX_CLAIMS,x as MAX_CLAIM_REFS,R as briefId,K as briefTerms,$ as briefToText,v as checkKnowledgeInvariants,h as contentHash,C as parseBriefText};
|