@chatpanel/gateway 0.6.110 → 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 -2296
- 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/prefs-store.js
CHANGED
|
@@ -1,149 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// gateway is the one address the extension and the desktop both have.
|
|
3
|
-
//
|
|
4
|
-
// A document of SECTIONS (the MCP server list, the skills, the search engines — see
|
|
5
|
-
// @chatpanel/events/client-prefs.js), each stamped with when it was last written. A client
|
|
6
|
-
// pushes the sections it changed with its own stamps; the store keeps the newer stamp per
|
|
7
|
-
// section and tells the pusher which of its sections lost, so it can take the other side's
|
|
8
|
-
// copy. Per-section last-writer-wins: a section is one screen a person edits, and merging two
|
|
9
|
-
// edits of one list key by key would make a list neither of them made.
|
|
10
|
-
//
|
|
11
|
-
// ENCRYPTED AT REST with the same device key as memory and history — an MCP server entry can
|
|
12
|
-
// carry an Authorization header, and this file must not be the plaintext copy of it.
|
|
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 { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
18
|
-
|
|
19
|
-
const DIR = join(os.homedir(), '.chatpanel');
|
|
20
|
-
const STORE_PATH = process.env.CHATPANEL_PREFS_STORE || join(DIR, 'prefs-store.enc');
|
|
21
|
-
const KEY_PATH = process.env.CHATPANEL_HISTORY_KEY || join(DIR, 'history-key');
|
|
22
|
-
|
|
23
|
-
/** A section id is a short word; anything else is refused before it is stored. */
|
|
24
|
-
const SECTION_ID_RE = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
25
|
-
/** One section's JSON, serialized — a list of a thousand MCP servers is not a preference. */
|
|
26
|
-
const MAX_SECTION_BYTES = 512 * 1024;
|
|
27
|
-
|
|
28
|
-
function loadOrCreateKey() {
|
|
29
|
-
try {
|
|
30
|
-
if (existsSync(KEY_PATH)) return Buffer.from(readFileSync(KEY_PATH, 'utf8').trim(), 'base64');
|
|
31
|
-
} catch { /* regenerate below */ }
|
|
32
|
-
const key = randomBytes(32);
|
|
33
|
-
mkdirSync(dirname(KEY_PATH), { recursive: true, mode: 0o700 });
|
|
34
|
-
writeFileSync(KEY_PATH, key.toString('base64'), { mode: 0o600 });
|
|
35
|
-
return key;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function encrypt(key, buf) {
|
|
39
|
-
const iv = randomBytes(12);
|
|
40
|
-
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
41
|
-
const ct = Buffer.concat([cipher.update(buf), cipher.final()]);
|
|
42
|
-
return { v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), ct: ct.toString('base64') };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function decrypt(key, env) {
|
|
46
|
-
const d = createDecipheriv('aes-256-gcm', key, Buffer.from(env.iv, 'base64'));
|
|
47
|
-
d.setAuthTag(Buffer.from(env.tag, 'base64'));
|
|
48
|
-
return Buffer.concat([d.update(Buffer.from(env.ct, 'base64')), d.final()]);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export class PrefsStore {
|
|
52
|
-
constructor({ storePath = STORE_PATH } = {}) {
|
|
53
|
-
this.path = storePath;
|
|
54
|
-
this._key = null;
|
|
55
|
-
this.sections = {}; // id -> { value, updatedAt, by }
|
|
56
|
-
this.revision = 0; // bumps on every accepted write, so a client can ask "anything new?"
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
load() {
|
|
60
|
-
this._key = loadOrCreateKey();
|
|
61
|
-
try {
|
|
62
|
-
if (existsSync(this.path)) {
|
|
63
|
-
const env = JSON.parse(readFileSync(this.path, 'utf8'));
|
|
64
|
-
const doc = JSON.parse(decrypt(this._key, env).toString('utf8'));
|
|
65
|
-
this.sections = doc?.sections && typeof doc.sections === 'object' ? doc.sections : {};
|
|
66
|
-
this.revision = Number(doc?.revision) || 0;
|
|
67
|
-
}
|
|
68
|
-
} catch {
|
|
69
|
-
// An unreadable store is an empty one, never a crash: the clients still hold their own
|
|
70
|
-
// copies and will push them back on the next change.
|
|
71
|
-
this.sections = {};
|
|
72
|
-
this.revision = 0;
|
|
73
|
-
}
|
|
74
|
-
return this;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
save() {
|
|
78
|
-
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
79
|
-
const env = encrypt(this._key, Buffer.from(JSON.stringify({ v: 1, revision: this.revision, sections: this.sections }), 'utf8'));
|
|
80
|
-
// Write beside, then rename: a crash mid-write leaves the old file, not half of a new one.
|
|
81
|
-
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
82
|
-
writeFileSync(tmp, JSON.stringify(env), { mode: 0o600 });
|
|
83
|
-
renameSync(tmp, this.path);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Every section, or one. Values are the caller's to keep — they are copies. */
|
|
87
|
-
get(id = '') {
|
|
88
|
-
if (id) {
|
|
89
|
-
const s = this.sections[id];
|
|
90
|
-
return s ? { [id]: { value: clone(s.value), updatedAt: s.updatedAt, by: s.by || '' } } : {};
|
|
91
|
-
}
|
|
92
|
-
const out = {};
|
|
93
|
-
for (const [k, s] of Object.entries(this.sections)) out[k] = { value: clone(s.value), updatedAt: s.updatedAt, by: s.by || '' };
|
|
94
|
-
return out;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Just the stamps — enough for a client to decide whether it needs the values. */
|
|
98
|
-
stamps() {
|
|
99
|
-
const out = {};
|
|
100
|
-
for (const [k, s] of Object.entries(this.sections)) out[k] = s.updatedAt;
|
|
101
|
-
return out;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Merge a client's stamped sections in. A section is taken when its stamp is newer than
|
|
106
|
-
* the one held (or nothing is held); otherwise the client is told it lost and gets the
|
|
107
|
-
* held copy back. Returns `{ applied, kept, sections }` where `sections` holds the current
|
|
108
|
-
* copies of everything the client sent — the client writes `kept` ones over its own.
|
|
109
|
-
*/
|
|
110
|
-
put(incoming, { by = '' } = {}) {
|
|
111
|
-
const applied = [];
|
|
112
|
-
const kept = [];
|
|
113
|
-
const sections = {};
|
|
114
|
-
for (const [id, entry] of Object.entries(incoming || {})) {
|
|
115
|
-
if (!SECTION_ID_RE.test(id)) continue;
|
|
116
|
-
const updatedAt = Number(entry?.updatedAt) || 0;
|
|
117
|
-
if (!updatedAt || entry?.value === undefined) continue;
|
|
118
|
-
let bytes;
|
|
119
|
-
try { bytes = Buffer.byteLength(JSON.stringify(entry.value), 'utf8'); } catch { continue; }
|
|
120
|
-
if (bytes > MAX_SECTION_BYTES) continue;
|
|
121
|
-
const held = this.sections[id];
|
|
122
|
-
if (!held || updatedAt > held.updatedAt) {
|
|
123
|
-
this.sections[id] = { value: clone(entry.value), updatedAt, by: String(by || '').slice(0, 40) };
|
|
124
|
-
applied.push(id);
|
|
125
|
-
} else {
|
|
126
|
-
kept.push(id);
|
|
127
|
-
}
|
|
128
|
-
const cur = this.sections[id];
|
|
129
|
-
sections[id] = { value: clone(cur.value), updatedAt: cur.updatedAt, by: cur.by || '' };
|
|
130
|
-
}
|
|
131
|
-
if (applied.length) { this.revision += 1; this.save(); }
|
|
132
|
-
return { applied, kept, sections, revision: this.revision };
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Forget one section entirely — the user removed the feature's settings, not just emptied them. */
|
|
136
|
-
remove(id) {
|
|
137
|
-
if (!this.sections[id]) return false;
|
|
138
|
-
delete this.sections[id];
|
|
139
|
-
this.revision += 1;
|
|
140
|
-
this.save();
|
|
141
|
-
return true;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
146
|
-
|
|
147
|
-
export function createPrefsStore(opts) {
|
|
148
|
-
return new PrefsStore(opts).load();
|
|
149
|
-
}
|
|
1
|
+
import{readFileSync as y,writeFileSync as m,existsSync as l,mkdirSync as S,renameSync as O}from"node:fs";import{join as h,dirname as b}from"node:path";import _ from"node:os";import{randomBytes as A,createCipheriv as N,createDecipheriv as T}from"node:crypto";const g=h(_.homedir(),".chatpanel"),E=process.env.CHATPANEL_PREFS_STORE||h(g,"prefs-store.enc"),c=process.env.CHATPANEL_HISTORY_KEY||h(g,"history-key"),k=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,B=512*1024;function J(){try{if(l(c))return Buffer.from(y(c,"utf8").trim(),"base64")}catch{}const i=A(32);return S(b(c),{recursive:!0,mode:448}),m(c,i.toString("base64"),{mode:384}),i}function P(i,t){const e=A(12),s=N("aes-256-gcm",i,e),n=Buffer.concat([s.update(t),s.final()]);return{v:1,iv:e.toString("base64"),tag:s.getAuthTag().toString("base64"),ct:n.toString("base64")}}function C(i,t){const e=T("aes-256-gcm",i,Buffer.from(t.iv,"base64"));return e.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([e.update(Buffer.from(t.ct,"base64")),e.final()])}class R{constructor({storePath:t=E}={}){this.path=t,this._key=null,this.sections={},this.revision=0}load(){this._key=J();try{if(l(this.path)){const t=JSON.parse(y(this.path,"utf8")),e=JSON.parse(C(this._key,t).toString("utf8"));this.sections=e?.sections&&typeof e.sections=="object"?e.sections:{},this.revision=Number(e?.revision)||0}}catch{this.sections={},this.revision=0}return this}save(){S(b(this.path),{recursive:!0,mode:448});const t=P(this._key,Buffer.from(JSON.stringify({v:1,revision:this.revision,sections:this.sections}),"utf8")),e=`${this.path}.${process.pid}.tmp`;m(e,JSON.stringify(t),{mode:384}),O(e,this.path)}get(t=""){if(t){const s=this.sections[t];return s?{[t]:{value:u(s.value),updatedAt:s.updatedAt,by:s.by||""}}:{}}const e={};for(const[s,n]of Object.entries(this.sections))e[s]={value:u(n.value),updatedAt:n.updatedAt,by:n.by||""};return e}stamps(){const t={};for(const[e,s]of Object.entries(this.sections))t[e]=s.updatedAt;return t}put(t,{by:e=""}={}){const s=[],n=[],p={};for(const[o,r]of Object.entries(t||{})){if(!k.test(o))continue;const a=Number(r?.updatedAt)||0;if(!a||r?.value===void 0)continue;let d;try{d=Buffer.byteLength(JSON.stringify(r.value),"utf8")}catch{continue}if(d>B)continue;const v=this.sections[o];!v||a>v.updatedAt?(this.sections[o]={value:u(r.value),updatedAt:a,by:String(e||"").slice(0,40)},s.push(o)):n.push(o);const f=this.sections[o];p[o]={value:u(f.value),updatedAt:f.updatedAt,by:f.by||""}}return s.length&&(this.revision+=1,this.save()),{applied:s,kept:n,sections:p,revision:this.revision}}remove(t){return this.sections[t]?(delete this.sections[t],this.revision+=1,this.save(),!0):!1}}const u=i=>i===void 0?void 0:JSON.parse(JSON.stringify(i));function x(i){return new R(i).load()}export{R as PrefsStore,x as createPrefsStore};
|
package/src/project-store.js
CHANGED
|
@@ -1,139 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// read (F8 §12). The page itself is data in the shared `projects` prefs section; this store
|
|
3
|
-
// holds the RECORD: the jobs posted on it, who applied and who was recruited, the runs it
|
|
4
|
-
// spawned and what they spent, the stakeholder's decisions, the report. Folded from events
|
|
5
|
-
// with the shared fold (project.js `foldProject`, vendored), so the desktop, the extension
|
|
6
|
-
// and this store never disagree on what a project is.
|
|
7
|
-
//
|
|
8
|
-
// Encrypted at rest with the team store's key, like the runs. Events append; nothing is
|
|
9
|
-
// edited; a watcher gets each event as it lands (the live project board).
|
|
10
|
-
|
|
11
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
|
|
12
|
-
import { join, dirname } from 'node:path';
|
|
13
|
-
import os from 'node:os';
|
|
14
|
-
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
15
|
-
import { emptyProjectRecord, foldProject, projectProgress, PROJECT_ID_RE } from './project.js';
|
|
16
|
-
import { normalizeJob, canTransition as canJobTransition } from './job.js';
|
|
17
|
-
|
|
18
|
-
const DIR = join(os.homedir(), '.chatpanel');
|
|
19
|
-
const STORE_PATH = process.env.CHATPANEL_PROJECTS_STORE || join(DIR, 'projects.enc');
|
|
20
|
-
const MAX_EVENTS_PER_PROJECT = 20_000;
|
|
21
|
-
const MAX_EVENT_BYTES = 64 * 1024;
|
|
22
|
-
|
|
23
|
-
function encrypt(key, buf) {
|
|
24
|
-
const iv = randomBytes(12);
|
|
25
|
-
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
26
|
-
const ct = Buffer.concat([cipher.update(buf), cipher.final()]);
|
|
27
|
-
return { v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), ct: ct.toString('base64') };
|
|
28
|
-
}
|
|
29
|
-
function decrypt(key, env) {
|
|
30
|
-
const d = createDecipheriv('aes-256-gcm', key, Buffer.from(env.iv, 'base64'));
|
|
31
|
-
d.setAuthTag(Buffer.from(env.tag, 'base64'));
|
|
32
|
-
return Buffer.concat([d.update(Buffer.from(env.ct, 'base64')), d.final()]);
|
|
33
|
-
}
|
|
34
|
-
const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
35
|
-
|
|
36
|
-
export class ProjectStore {
|
|
37
|
-
constructor({ storePath = STORE_PATH, key = null, now = () => Date.now() } = {}) {
|
|
38
|
-
this.path = storePath;
|
|
39
|
-
this.key = key;
|
|
40
|
-
this.now = now;
|
|
41
|
-
this.projects = new Map(); // id -> { ...record, events: [] }
|
|
42
|
-
this.watchers = new Map(); // id -> Set<fn(ev)>
|
|
43
|
-
}
|
|
44
|
-
load() {
|
|
45
|
-
try {
|
|
46
|
-
if (existsSync(this.path) && this.key) {
|
|
47
|
-
const env = JSON.parse(readFileSync(this.path, 'utf8'));
|
|
48
|
-
const doc = JSON.parse(decrypt(this.key, env).toString('utf8'));
|
|
49
|
-
for (const p of Array.isArray(doc?.projects) ? doc.projects : []) if (p?.id) this.projects.set(p.id, p);
|
|
50
|
-
}
|
|
51
|
-
} catch { this.projects = new Map(); }
|
|
52
|
-
return this;
|
|
53
|
-
}
|
|
54
|
-
save() {
|
|
55
|
-
if (!this.key) return;
|
|
56
|
-
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
57
|
-
const env = encrypt(this.key, Buffer.from(JSON.stringify({ v: 1, projects: [...this.projects.values()] }), 'utf8'));
|
|
58
|
-
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
59
|
-
writeFileSync(tmp, JSON.stringify(env), { mode: 0o600 });
|
|
60
|
-
renameSync(tmp, this.path);
|
|
61
|
-
}
|
|
62
|
-
_view(rec, { events = false } = {}) {
|
|
63
|
-
const v = clone({ ...rec, events: undefined });
|
|
64
|
-
delete v.events;
|
|
65
|
-
v.progress = projectProgress(v);
|
|
66
|
-
if (events) v.events = clone(rec.events);
|
|
67
|
-
return v;
|
|
68
|
-
}
|
|
69
|
-
/** Open a record for a page (idempotent: a page saved twice is one record). */
|
|
70
|
-
create({ id, project = null, by = 'person' } = {}) {
|
|
71
|
-
if (!PROJECT_ID_RE.test(String(id || ''))) throw new Error('project id: a short identifier');
|
|
72
|
-
let rec = this.projects.get(id);
|
|
73
|
-
if (!rec) { rec = { ...emptyProjectRecord({ id, now: this.now() }), events: [] }; this.projects.set(id, rec); }
|
|
74
|
-
if (project) this.append(id, [{ type: rec.page ? 'project.updated' : 'project.created', at: this.now(), project: { ...project, id }, by }]);
|
|
75
|
-
else this.save();
|
|
76
|
-
return this._view(rec);
|
|
77
|
-
}
|
|
78
|
-
append(id, events) {
|
|
79
|
-
const rec = this.projects.get(String(id || ''));
|
|
80
|
-
if (!rec) throw new Error(`no project ${id}`);
|
|
81
|
-
const list = Array.isArray(events) ? events : [events];
|
|
82
|
-
let seq = rec.events.length;
|
|
83
|
-
for (const e of list) {
|
|
84
|
-
if (!e || typeof e !== 'object' || !e.type) continue;
|
|
85
|
-
let bytes; try { bytes = Buffer.byteLength(JSON.stringify(e), 'utf8'); } catch { continue; }
|
|
86
|
-
if (bytes > MAX_EVENT_BYTES) continue;
|
|
87
|
-
if (rec.events.length >= MAX_EVENTS_PER_PROJECT) break;
|
|
88
|
-
const { type, at, ...payload } = e;
|
|
89
|
-
const ev = { seq: seq++, type: String(type), at: Number(at) || this.now(), payload };
|
|
90
|
-
rec.events.push(ev);
|
|
91
|
-
foldProject(rec, ev);
|
|
92
|
-
for (const fn of this.watchers.get(rec.id) || []) { try { fn(ev); } catch { /* a dead watcher */ } }
|
|
93
|
-
}
|
|
94
|
-
this.save();
|
|
95
|
-
return this._view(rec);
|
|
96
|
-
}
|
|
97
|
-
get(id, opts) { const r = this.projects.get(String(id || '')); return r ? this._view(r, opts) : null; }
|
|
98
|
-
/** Newest activity first; the list a board shows — jobs counted, not listed. */
|
|
99
|
-
list({ limit = 50, status = '' } = {}) {
|
|
100
|
-
return [...this.projects.values()]
|
|
101
|
-
.filter((r) => !status || r.status === status)
|
|
102
|
-
.sort((a, b) => b.lastEventAt - a.lastEventAt)
|
|
103
|
-
.slice(0, Math.max(1, Math.min(200, Number(limit) || 50)))
|
|
104
|
-
.map((r) => { const v = this._view(r); return { ...v, jobs: undefined, decisions: undefined, report: undefined, runs: undefined, jobCount: r.jobs.length, runCount: r.runs.length }; });
|
|
105
|
-
}
|
|
106
|
-
/** Every open posting across projects — the job board. */
|
|
107
|
-
openJobs() {
|
|
108
|
-
return [...this.projects.values()].flatMap((r) => r.jobs.filter((j) => ['open', 'evaluating', 'recruited'].includes(j.status)).map((j) => ({ ...j, projectTitle: r.page?.title || r.id })));
|
|
109
|
-
}
|
|
110
|
-
/** Post a job on a project: validated as a posting, appended as an event. */
|
|
111
|
-
postJob(id, job, { by = 'person' } = {}) {
|
|
112
|
-
const rec = this.projects.get(String(id || ''));
|
|
113
|
-
if (!rec) throw new Error(`no project ${id}`);
|
|
114
|
-
const j = normalizeJob({ ...job, projectId: rec.id, postedBy: job?.postedBy || by });
|
|
115
|
-
if (rec.jobs.some((x) => x.id === j.id)) throw new Error(`job ${j.id} already exists`);
|
|
116
|
-
return this.append(rec.id, [{ type: 'job.posted', at: this.now(), job: j, by }]);
|
|
117
|
-
}
|
|
118
|
-
/** Move a job along its machine, or update its fields (applications, recruited, result). */
|
|
119
|
-
updateJob(id, jobId, patch, { by = 'person' } = {}) {
|
|
120
|
-
const rec = this.projects.get(String(id || ''));
|
|
121
|
-
if (!rec) throw new Error(`no project ${id}`);
|
|
122
|
-
const cur = rec.jobs.find((x) => x.id === jobId);
|
|
123
|
-
if (!cur) throw new Error(`no job ${jobId}`);
|
|
124
|
-
if (patch?.status && patch.status !== cur.status && !canJobTransition(cur.status, patch.status)) throw new Error(`a job cannot go from ${cur.status} to ${patch.status}`);
|
|
125
|
-
const allowed = ['status', 'applications', 'recruited', 'runId', 'result', 'workspace', 'budget', 'brief', 'title', 'needs', 'dependsOn'];
|
|
126
|
-
const job = { id: jobId };
|
|
127
|
-
for (const k of allowed) if (patch?.[k] !== undefined) job[k] = patch[k];
|
|
128
|
-
return this.append(rec.id, [{ type: 'job.updated', at: this.now(), job, by }]);
|
|
129
|
-
}
|
|
130
|
-
watch(id, fn) {
|
|
131
|
-
const set = this.watchers.get(String(id)) || new Set();
|
|
132
|
-
set.add(fn); this.watchers.set(String(id), set);
|
|
133
|
-
return () => { set.delete(fn); };
|
|
134
|
-
}
|
|
135
|
-
eventsSince(id, after = -1) { const r = this.projects.get(String(id || '')); return r ? r.events.filter((e) => e.seq > after) : []; }
|
|
136
|
-
remove(id) { const had = this.projects.delete(String(id || '')); if (had) this.save(); return had; }
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export function createProjectStore(opts) { return new ProjectStore(opts).load(); }
|
|
1
|
+
import{readFileSync as g,writeFileSync as j,existsSync as w,mkdirSync as m,renameSync as y}from"node:fs";import{join as f,dirname as v}from"node:path";import S from"node:os";import{randomBytes as b,createCipheriv as E,createDecipheriv as _}from"node:crypto";import{emptyProjectRecord as J,foldProject as T,projectProgress as A,PROJECT_ID_RE as O}from"./project.js";import{normalizeJob as N,canTransition as B}from"./job.js";const P=f(S.homedir(),".chatpanel"),k=process.env.CHATPANEL_PROJECTS_STORE||f(P,"projects.enc"),R=2e4,$=64*1024;function M(n,r){const e=b(12),t=E("aes-256-gcm",n,e),s=Buffer.concat([t.update(r),t.final()]);return{v:1,iv:e.toString("base64"),tag:t.getAuthTag().toString("base64"),ct:s.toString("base64")}}function C(n,r){const e=_("aes-256-gcm",n,Buffer.from(r.iv,"base64"));return e.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([e.update(Buffer.from(r.ct,"base64")),e.final()])}const h=n=>n===void 0?void 0:JSON.parse(JSON.stringify(n));class x{constructor({storePath:r=k,key:e=null,now:t=()=>Date.now()}={}){this.path=r,this.key=e,this.now=t,this.projects=new Map,this.watchers=new Map}load(){try{if(w(this.path)&&this.key){const r=JSON.parse(g(this.path,"utf8")),e=JSON.parse(C(this.key,r).toString("utf8"));for(const t of Array.isArray(e?.projects)?e.projects:[])t?.id&&this.projects.set(t.id,t)}}catch{this.projects=new Map}return this}save(){if(!this.key)return;m(v(this.path),{recursive:!0,mode:448});const r=M(this.key,Buffer.from(JSON.stringify({v:1,projects:[...this.projects.values()]}),"utf8")),e=`${this.path}.${process.pid}.tmp`;j(e,JSON.stringify(r),{mode:384}),y(e,this.path)}_view(r,{events:e=!1}={}){const t=h({...r,events:void 0});return delete t.events,t.progress=A(t),e&&(t.events=h(r.events)),t}create({id:r,project:e=null,by:t="person"}={}){if(!O.test(String(r||"")))throw new Error("project id: a short identifier");let s=this.projects.get(r);return s||(s={...J({id:r,now:this.now()}),events:[]},this.projects.set(r,s)),e?this.append(r,[{type:s.page?"project.updated":"project.created",at:this.now(),project:{...e,id:r},by:t}]):this.save(),this._view(s)}append(r,e){const t=this.projects.get(String(r||""));if(!t)throw new Error(`no project ${r}`);const s=Array.isArray(e)?e:[e];let i=t.events.length;for(const o of s){if(!o||typeof o!="object"||!o.type)continue;let a;try{a=Buffer.byteLength(JSON.stringify(o),"utf8")}catch{continue}if(a>$)continue;if(t.events.length>=R)break;const{type:p,at:c,...d}=o,u={seq:i++,type:String(p),at:Number(c)||this.now(),payload:d};t.events.push(u),T(t,u);for(const l of this.watchers.get(t.id)||[])try{l(u)}catch{}}return this.save(),this._view(t)}get(r,e){const t=this.projects.get(String(r||""));return t?this._view(t,e):null}list({limit:r=50,status:e=""}={}){return[...this.projects.values()].filter(t=>!e||t.status===e).sort((t,s)=>s.lastEventAt-t.lastEventAt).slice(0,Math.max(1,Math.min(200,Number(r)||50))).map(t=>({...this._view(t),jobs:void 0,decisions:void 0,report:void 0,runs:void 0,jobCount:t.jobs.length,runCount:t.runs.length}))}openJobs(){return[...this.projects.values()].flatMap(r=>r.jobs.filter(e=>["open","evaluating","recruited"].includes(e.status)).map(e=>({...e,projectTitle:r.page?.title||r.id})))}postJob(r,e,{by:t="person"}={}){const s=this.projects.get(String(r||""));if(!s)throw new Error(`no project ${r}`);const i=N({...e,projectId:s.id,postedBy:e?.postedBy||t});if(s.jobs.some(o=>o.id===i.id))throw new Error(`job ${i.id} already exists`);return this.append(s.id,[{type:"job.posted",at:this.now(),job:i,by:t}])}updateJob(r,e,t,{by:s="person"}={}){const i=this.projects.get(String(r||""));if(!i)throw new Error(`no project ${r}`);const o=i.jobs.find(c=>c.id===e);if(!o)throw new Error(`no job ${e}`);if(t?.status&&t.status!==o.status&&!B(o.status,t.status))throw new Error(`a job cannot go from ${o.status} to ${t.status}`);const a=["status","applications","recruited","runId","result","workspace","budget","brief","title","needs","dependsOn"],p={id:e};for(const c of a)t?.[c]!==void 0&&(p[c]=t[c]);return this.append(i.id,[{type:"job.updated",at:this.now(),job:p,by:s}])}watch(r,e){const t=this.watchers.get(String(r))||new Set;return t.add(e),this.watchers.set(String(r),t),()=>{t.delete(e)}}eventsSince(r,e=-1){const t=this.projects.get(String(r||""));return t?t.events.filter(s=>s.seq>e):[]}remove(r){const e=this.projects.delete(String(r||""));return e&&this.save(),e}}function V(n){return new x(n).load()}export{x as ProjectStore,V as createProjectStore};
|
package/src/project.js
CHANGED
|
@@ -1,171 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// A project — the page a goal starts on, and the record that folds everything done for it.
|
|
3
|
-
//
|
|
4
|
-
// Every job or goal starts here (F8 §12): the goal, defined by its stakeholder — the *chief
|
|
5
|
-
// executive*: a person by default, an agent from the pool when the person delegates it —
|
|
6
|
-
// with a done-when a run can be checked against, a budget the jobs are carved from, the
|
|
7
|
-
// repos the work happens in, and the gate that says how far a team may go without a person.
|
|
8
|
-
// A project is data (a `projects` prefs section, both clients) and a gateway record that
|
|
9
|
-
// folds its jobs, runs and spend from events, the way a run folds (team-record.js).
|
|
10
|
-
//
|
|
11
|
-
// A project's status is a small machine: draft (a goal being written) → open (jobs may be
|
|
12
|
-
// posted) → active (a job was recruited) → done (done-when held, a person closed it) or
|
|
13
|
-
// closed (abandoned). Nothing here runs anything: project-run.js is the executive loop.
|
|
14
|
-
|
|
15
|
-
import { validateBudget, normalizeBudget } from './budget.js';
|
|
16
|
-
import { normalizeGate, validateGate } from './gate.js';
|
|
17
|
-
|
|
18
|
-
export const PROJECT_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
|
|
19
|
-
export const PROJECT_STATUSES = Object.freeze(['draft', 'open', 'active', 'done', 'closed']);
|
|
20
|
-
const NEXT = Object.freeze({ draft: ['open', 'closed'], open: ['active', 'closed', 'draft'], active: ['done', 'closed', 'open'], done: ['closed', 'open'], closed: ['open'] });
|
|
21
|
-
export const MAX_REPOS = 16;
|
|
22
|
-
|
|
23
|
-
export class ProjectError extends Error {
|
|
24
|
-
constructor(code, message) { super(message); this.name = 'ProjectError'; this.code = code; }
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
28
|
-
const clip = (s, n) => String(s || '').trim().slice(0, n);
|
|
29
|
-
|
|
30
|
-
export function validateProject(p) {
|
|
31
|
-
const errors = [];
|
|
32
|
-
if (!isRecord(p)) return { ok: false, errors: ['project must be an object'] };
|
|
33
|
-
if (!PROJECT_ID_RE.test(String(p.id || ''))) errors.push('id: a short identifier (letters, digits, _ -)');
|
|
34
|
-
if (!clip(p.title, 200)) errors.push('title: what the project is called');
|
|
35
|
-
if (!clip(p.goal, 4000)) errors.push('goal: what done looks like, in the stakeholder\'s words');
|
|
36
|
-
if (p.doneWhen !== undefined && !clip(p.doneWhen, 2000)) errors.push('doneWhen: a check a run can be held to, or leave it out');
|
|
37
|
-
if (p.stakeholder !== undefined && p.stakeholder !== 'person' && !/^[a-z][a-z0-9_-]{0,63}$/i.test(String(p.stakeholder))) errors.push('stakeholder: "person" or an agent id');
|
|
38
|
-
if (p.status !== undefined && !PROJECT_STATUSES.includes(p.status)) errors.push(`status: one of ${PROJECT_STATUSES.join(', ')}`);
|
|
39
|
-
const b = validateBudget(p.budget);
|
|
40
|
-
if (!b.ok) errors.push(...b.errors.map((e) => `budget: ${e}`));
|
|
41
|
-
if (p.repos !== undefined) {
|
|
42
|
-
if (!Array.isArray(p.repos)) errors.push('repos: a list of repo ids');
|
|
43
|
-
else if (p.repos.length > MAX_REPOS) errors.push(`repos: at most ${MAX_REPOS}`);
|
|
44
|
-
}
|
|
45
|
-
if (p.gate !== undefined && p.gate !== null) errors.push(...validateGate(p.gate, { partial: true }).errors.map((e) => `gate: ${e}`));
|
|
46
|
-
return { ok: errors.length === 0, errors };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** The stored form: defaults filled, the budget normalised, the gate (if any) normalised. */
|
|
50
|
-
export function normalizeProject(p) {
|
|
51
|
-
const v = validateProject(p);
|
|
52
|
-
if (!v.ok) throw new ProjectError('INVALID', v.errors.join('; '));
|
|
53
|
-
return {
|
|
54
|
-
id: String(p.id),
|
|
55
|
-
title: clip(p.title, 200),
|
|
56
|
-
goal: clip(p.goal, 4000),
|
|
57
|
-
doneWhen: clip(p.doneWhen, 2000),
|
|
58
|
-
stakeholder: p.stakeholder ? String(p.stakeholder) : 'person',
|
|
59
|
-
budget: normalizeBudget(p.budget),
|
|
60
|
-
status: PROJECT_STATUSES.includes(p.status) ? p.status : 'draft',
|
|
61
|
-
repos: Array.isArray(p.repos) ? [...new Set(p.repos.map((r) => clip(r, 120)).filter(Boolean))].slice(0, MAX_REPOS) : [],
|
|
62
|
-
...(p.gate ? { gate: normalizeGate(p.gate, { partial: true }) } : {}),
|
|
63
|
-
tags: Array.isArray(p.tags) ? [...new Set(p.tags.map((t) => clip(t, 40)).filter(Boolean))].slice(0, 12) : [],
|
|
64
|
-
createdBy: clip(p.createdBy, 80) || 'person',
|
|
65
|
-
createdAt: Number(p.createdAt) || Date.now(),
|
|
66
|
-
...(p.updatedAt ? { updatedAt: Number(p.updatedAt) } : {}),
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function defineProject(p) { return Object.freeze(normalizeProject(p)); }
|
|
71
|
-
|
|
72
|
-
/** May the project move from `from` to `to`? The machine above; a person's close is always allowed. */
|
|
73
|
-
export function canTransition(from, to) {
|
|
74
|
-
return (NEXT[from] || []).includes(to);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** A blank page for the form. */
|
|
78
|
-
export function blankProject() {
|
|
79
|
-
return { id: '', title: '', goal: '', doneWhen: '', stakeholder: 'person', budget: { tokens: 200000, ms: 3600000 }, status: 'draft', repos: [], tags: [] };
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** The form → a project, or the errors (the same shaping both clients use). */
|
|
83
|
-
export function projectFromForm(form) {
|
|
84
|
-
const budget = {};
|
|
85
|
-
for (const k of ['tokens', 'calls', 'ms', 'usd']) {
|
|
86
|
-
const v = Number(form?.budget?.[k]);
|
|
87
|
-
if (form?.budget?.[k] !== '' && form?.budget?.[k] != null && Number.isFinite(v) && v > 0) budget[k] = v;
|
|
88
|
-
}
|
|
89
|
-
const p = {
|
|
90
|
-
id: String(form?.id || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[^a-z]+/, '').replace(/-+$/, '').slice(0, 64),
|
|
91
|
-
title: form?.title, goal: form?.goal, doneWhen: form?.doneWhen, stakeholder: form?.stakeholder || 'person',
|
|
92
|
-
budget, status: form?.status || 'draft',
|
|
93
|
-
repos: String(Array.isArray(form?.repos) ? form.repos.join(',') : form?.repos || '').split(/[,\s]+/).filter(Boolean),
|
|
94
|
-
tags: String(Array.isArray(form?.tags) ? form.tags.join(',') : form?.tags || '').split(/[,\s]+/).filter(Boolean),
|
|
95
|
-
...(form?.gate ? { gate: form.gate } : {}), ...(form?.createdAt ? { createdAt: form.createdAt } : {}),
|
|
96
|
-
};
|
|
97
|
-
const v = validateProject(p);
|
|
98
|
-
return v.ok ? { ok: true, project: normalizeProject(p) } : { ok: false, errors: v.errors };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// ── the record: a project folded from its events ────────────────────────────────────────
|
|
102
|
-
|
|
103
|
-
/** The empty record — what the gateway holds per project and both clients read. */
|
|
104
|
-
export function emptyProjectRecord({ id, now = Date.now() } = {}) {
|
|
105
|
-
return { id, page: null, status: 'draft', jobs: [], runs: [], spend: { tokens: 0, calls: 0, usd: 0, ms: 0 }, decisions: [], report: null, createdAt: now, lastEventAt: now };
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Fold one event into the record. Events: `project.created` `{ project }` · `project.updated`
|
|
110
|
-
* `{ project }` · `project.status` `{ status, by, note }` · `job.posted` `{ job }` ·
|
|
111
|
-
* `job.updated` `{ job }` (any field: applications, recruited, status) · `run.linked`
|
|
112
|
-
* `{ runId, jobId }` · `run.spent` `{ runId, spent }` · `project.decision` `{ by, kind, text,
|
|
113
|
-
* refs }` · `project.report` `{ text, by }`. Idempotent by job id and run id.
|
|
114
|
-
*/
|
|
115
|
-
export function foldProject(rec, ev) {
|
|
116
|
-
const type = String(ev?.type || '');
|
|
117
|
-
const p = ev?.payload && typeof ev.payload === 'object' ? ev.payload : (ev || {});
|
|
118
|
-
const at = Number(ev?.at) || Date.now();
|
|
119
|
-
rec.lastEventAt = at;
|
|
120
|
-
switch (type) {
|
|
121
|
-
case 'project.created':
|
|
122
|
-
case 'project.updated':
|
|
123
|
-
if (p.project && typeof p.project === 'object') { rec.page = { ...p.project, updatedAt: at }; rec.status = p.project.status || rec.status; }
|
|
124
|
-
break;
|
|
125
|
-
case 'project.status':
|
|
126
|
-
if (PROJECT_STATUSES.includes(p.status)) { rec.status = p.status; if (rec.page) rec.page.status = p.status; rec.decisions.push({ at, by: p.by || 'person', kind: 'status', text: `${p.status}${p.note ? ` — ${p.note}` : ''}` }); }
|
|
127
|
-
break;
|
|
128
|
-
case 'job.posted':
|
|
129
|
-
if (p.job?.id && !rec.jobs.some((j) => j.id === p.job.id)) rec.jobs.push({ ...p.job, postedAt: at });
|
|
130
|
-
if (rec.status === 'draft') rec.status = 'open';
|
|
131
|
-
break;
|
|
132
|
-
case 'job.updated': {
|
|
133
|
-
const i = rec.jobs.findIndex((j) => j.id === p.job?.id);
|
|
134
|
-
if (i >= 0) rec.jobs[i] = { ...rec.jobs[i], ...p.job, updatedAt: at };
|
|
135
|
-
if (p.job?.status === 'recruited' || p.job?.status === 'in-progress') { if (rec.status === 'open' || rec.status === 'draft') rec.status = 'active'; }
|
|
136
|
-
break;
|
|
137
|
-
}
|
|
138
|
-
case 'run.linked':
|
|
139
|
-
if (p.runId && !rec.runs.some((r) => r.runId === p.runId)) rec.runs.push({ runId: p.runId, jobId: p.jobId || null, at });
|
|
140
|
-
break;
|
|
141
|
-
case 'run.spent': {
|
|
142
|
-
const r = rec.runs.find((x) => x.runId === p.runId);
|
|
143
|
-
const prev = r?.spent || { tokens: 0, calls: 0, usd: 0, ms: 0 };
|
|
144
|
-
const next = { tokens: Number(p.spent?.tokens) || 0, calls: Number(p.spent?.calls) || 0, usd: Number(p.spent?.usd) || 0, ms: Number(p.spent?.ms) || 0 };
|
|
145
|
-
// A run reports its running total; the project's spend is the sum of every run's latest.
|
|
146
|
-
for (const k of Object.keys(next)) rec.spend[k] = Math.max(0, (rec.spend[k] || 0) - (prev[k] || 0) + next[k]);
|
|
147
|
-
if (r) r.spent = next; else rec.runs.push({ runId: p.runId, jobId: null, at, spent: next });
|
|
148
|
-
break;
|
|
149
|
-
}
|
|
150
|
-
case 'project.decision':
|
|
151
|
-
rec.decisions.push({ at, by: p.by || 'person', kind: p.kind || 'note', text: String(p.text || '').slice(0, 2000), refs: Array.isArray(p.refs) ? p.refs.slice(0, 8) : [] });
|
|
152
|
-
break;
|
|
153
|
-
case 'project.report':
|
|
154
|
-
rec.report = { text: String(p.text || ''), by: p.by || 'runner', at };
|
|
155
|
-
break;
|
|
156
|
-
default: break;
|
|
157
|
-
}
|
|
158
|
-
return rec;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** How far along: jobs by status, spend against the budget, whether done-when is claimed. */
|
|
162
|
-
export function projectProgress(rec) {
|
|
163
|
-
const by = {};
|
|
164
|
-
for (const j of rec?.jobs || []) by[j.status] = (by[j.status] || 0) + 1;
|
|
165
|
-
const cap = rec?.page?.budget || {};
|
|
166
|
-
const spend = rec?.spend || {};
|
|
167
|
-
const pct = cap.tokens ? Math.min(1, (spend.tokens || 0) / cap.tokens) : cap.usd ? Math.min(1, (spend.usd || 0) / cap.usd) : cap.ms ? Math.min(1, (spend.ms || 0) / cap.ms) : null;
|
|
168
|
-
const total = (rec?.jobs || []).length;
|
|
169
|
-
const done = by.done || 0;
|
|
170
|
-
return { jobs: { total, by }, done, open: (by.open || 0) + (by.evaluating || 0) + (by.recruited || 0) + (by['in-progress'] || 0), spend, cap, budgetUsed: pct, hasReport: !!rec?.report, status: rec?.status || 'draft' };
|
|
171
|
-
}
|
|
1
|
+
import{validateBudget as g,normalizeBudget as f}from"./budget.js";import{normalizeGate as j,validateGate as h}from"./gate.js";const k=/^[a-z][a-z0-9_-]{0,63}$/i,l=Object.freeze(["draft","open","active","done","closed"]),y=Object.freeze({draft:["open","closed"],open:["active","closed","draft"],active:["done","closed","open"],done:["closed","open"],closed:["open"]}),c=16;class A extends Error{constructor(s,o){super(o),this.name="ProjectError",this.code=s}}const m=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=(t,s)=>String(t||"").trim().slice(0,s);function p(t){const s=[];if(!m(t))return{ok:!1,errors:["project must be an object"]};k.test(String(t.id||""))||s.push("id: a short identifier (letters, digits, _ -)"),a(t.title,200)||s.push("title: what the project is called"),a(t.goal,4e3)||s.push("goal: what done looks like, in the stakeholder's words"),t.doneWhen!==void 0&&!a(t.doneWhen,2e3)&&s.push("doneWhen: a check a run can be held to, or leave it out"),t.stakeholder!==void 0&&t.stakeholder!=="person"&&!/^[a-z][a-z0-9_-]{0,63}$/i.test(String(t.stakeholder))&&s.push('stakeholder: "person" or an agent id'),t.status!==void 0&&!l.includes(t.status)&&s.push(`status: one of ${l.join(", ")}`);const o=g(t.budget);return o.ok||s.push(...o.errors.map(e=>`budget: ${e}`)),t.repos!==void 0&&(Array.isArray(t.repos)?t.repos.length>c&&s.push(`repos: at most ${c}`):s.push("repos: a list of repo ids")),t.gate!==void 0&&t.gate!==null&&s.push(...h(t.gate,{partial:!0}).errors.map(e=>`gate: ${e}`)),{ok:s.length===0,errors:s}}function b(t){const s=p(t);if(!s.ok)throw new A("INVALID",s.errors.join("; "));return{id:String(t.id),title:a(t.title,200),goal:a(t.goal,4e3),doneWhen:a(t.doneWhen,2e3),stakeholder:t.stakeholder?String(t.stakeholder):"person",budget:f(t.budget),status:l.includes(t.status)?t.status:"draft",repos:Array.isArray(t.repos)?[...new Set(t.repos.map(o=>a(o,120)).filter(Boolean))].slice(0,c):[],...t.gate?{gate:j(t.gate,{partial:!0})}:{},tags:Array.isArray(t.tags)?[...new Set(t.tags.map(o=>a(o,40)).filter(Boolean))].slice(0,12):[],createdBy:a(t.createdBy,80)||"person",createdAt:Number(t.createdAt)||Date.now(),...t.updatedAt?{updatedAt:Number(t.updatedAt)}:{}}}function I(t){return Object.freeze(b(t))}function z(t,s){return(y[t]||[]).includes(s)}function P(){return{id:"",title:"",goal:"",doneWhen:"",stakeholder:"person",budget:{tokens:2e5,ms:36e5},status:"draft",repos:[],tags:[]}}function w(t){const s={};for(const n of["tokens","calls","ms","usd"]){const r=Number(t?.budget?.[n]);t?.budget?.[n]!==""&&t?.budget?.[n]!=null&&Number.isFinite(r)&&r>0&&(s[n]=r)}const o={id:String(t?.id||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64),title:t?.title,goal:t?.goal,doneWhen:t?.doneWhen,stakeholder:t?.stakeholder||"person",budget:s,status:t?.status||"draft",repos:String(Array.isArray(t?.repos)?t.repos.join(","):t?.repos||"").split(/[,\s]+/).filter(Boolean),tags:String(Array.isArray(t?.tags)?t.tags.join(","):t?.tags||"").split(/[,\s]+/).filter(Boolean),...t?.gate?{gate:t.gate}:{},...t?.createdAt?{createdAt:t.createdAt}:{}},e=p(o);return e.ok?{ok:!0,project:b(o)}:{ok:!1,errors:e.errors}}function E({id:t,now:s=Date.now()}={}){return{id:t,page:null,status:"draft",jobs:[],runs:[],spend:{tokens:0,calls:0,usd:0,ms:0},decisions:[],report:null,createdAt:s,lastEventAt:s}}function N(t,s){const o=String(s?.type||""),e=s?.payload&&typeof s.payload=="object"?s.payload:s||{},n=Number(s?.at)||Date.now();switch(t.lastEventAt=n,o){case"project.created":case"project.updated":e.project&&typeof e.project=="object"&&(t.page={...e.project,updatedAt:n},t.status=e.project.status||t.status);break;case"project.status":l.includes(e.status)&&(t.status=e.status,t.page&&(t.page.status=e.status),t.decisions.push({at:n,by:e.by||"person",kind:"status",text:`${e.status}${e.note?` — ${e.note}`:""}`}));break;case"job.posted":e.job?.id&&!t.jobs.some(r=>r.id===e.job.id)&&t.jobs.push({...e.job,postedAt:n}),t.status==="draft"&&(t.status="open");break;case"job.updated":{const r=t.jobs.findIndex(u=>u.id===e.job?.id);r>=0&&(t.jobs[r]={...t.jobs[r],...e.job,updatedAt:n}),(e.job?.status==="recruited"||e.job?.status==="in-progress")&&(t.status==="open"||t.status==="draft")&&(t.status="active");break}case"run.linked":e.runId&&!t.runs.some(r=>r.runId===e.runId)&&t.runs.push({runId:e.runId,jobId:e.jobId||null,at:n});break;case"run.spent":{const r=t.runs.find(i=>i.runId===e.runId),u=r?.spent||{tokens:0,calls:0,usd:0,ms:0},d={tokens:Number(e.spent?.tokens)||0,calls:Number(e.spent?.calls)||0,usd:Number(e.spent?.usd)||0,ms:Number(e.spent?.ms)||0};for(const i of Object.keys(d))t.spend[i]=Math.max(0,(t.spend[i]||0)-(u[i]||0)+d[i]);r?r.spent=d:t.runs.push({runId:e.runId,jobId:null,at:n,spent:d});break}case"project.decision":t.decisions.push({at:n,by:e.by||"person",kind:e.kind||"note",text:String(e.text||"").slice(0,2e3),refs:Array.isArray(e.refs)?e.refs.slice(0,8):[]});break;case"project.report":t.report={text:String(e.text||""),by:e.by||"runner",at:n};break;default:break}return t}function $(t){const s={};for(const d of t?.jobs||[])s[d.status]=(s[d.status]||0)+1;const o=t?.page?.budget||{},e=t?.spend||{},n=o.tokens?Math.min(1,(e.tokens||0)/o.tokens):o.usd?Math.min(1,(e.usd||0)/o.usd):o.ms?Math.min(1,(e.ms||0)/o.ms):null,r=(t?.jobs||[]).length,u=s.done||0;return{jobs:{total:r,by:s},done:u,open:(s.open||0)+(s.evaluating||0)+(s.recruited||0)+(s["in-progress"]||0),spend:e,cap:o,budgetUsed:n,hasReport:!!t?.report,status:t?.status||"draft"}}export{c as MAX_REPOS,k as PROJECT_ID_RE,l as PROJECT_STATUSES,A as ProjectError,P as blankProject,z as canTransition,I as defineProject,E as emptyProjectRecord,N as foldProject,b as normalizeProject,w as projectFromForm,$ as projectProgress,p as validateProject};
|