@profullstack/gov-contracts 0.0.0-stage → 0.2.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/src/profile.js ADDED
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The bidder's niche profile, derived from its own website.
3
+ *
4
+ * crawl (spider.js, c0mpute crawl.fetch first) -> index the pages (SQLite
5
+ * FTS5) -> a model names the niches, keywords, NAICS and non-fits from what
6
+ * the pages say (c0mpute first, OpenAI/Claude fallback) -> save as the active
7
+ * profile -> re-screen every open solicitation against it.
8
+ *
9
+ * Without a model, niches come from NICHE_LIBRARY: a niche is kept when the
10
+ * site's own text uses its keywords. An operator can edit the result.
11
+ */
12
+ import { z } from 'zod';
13
+ import { makeAi } from './ai.js';
14
+ import { DEFAULT_PROFILE, NICHE_LIBRARY, BASE_NEGATIVE, activeProfile, compile, keywordFragment, nicheMatch, normalizeProfile, setActiveProfile } from './niche.js';
15
+ import { crawlSite } from './spider.js';
16
+ import { logRun, now, openDb } from './store.js';
17
+
18
+ /* ------------------------------------------------------------------ storage -- */
19
+
20
+ let ready = false;
21
+ function db() {
22
+ const d = openDb();
23
+ if (ready) return d;
24
+ d.exec(`
25
+ CREATE TABLE IF NOT EXISTS profile (
26
+ id TEXT PRIMARY KEY, -- 'active'
27
+ domain TEXT,
28
+ data TEXT NOT NULL, -- JSON profile (niche.js normalizeProfile)
29
+ updated_at TEXT NOT NULL
30
+ );
31
+ CREATE TABLE IF NOT EXISTS profile_pages (
32
+ url TEXT PRIMARY KEY,
33
+ domain TEXT NOT NULL,
34
+ title TEXT,
35
+ description TEXT,
36
+ headings TEXT, -- JSON array
37
+ text TEXT,
38
+ via TEXT, -- c0mpute:bridge | c0mpute:cli | direct | pushed
39
+ fetched_at TEXT NOT NULL
40
+ );
41
+ CREATE INDEX IF NOT EXISTS pp_domain ON profile_pages(domain);
42
+ CREATE VIRTUAL TABLE IF NOT EXISTS profile_pages_fts USING fts5(url UNINDEXED, title, headings, text, tokenize = 'porter');
43
+ `);
44
+ ready = true;
45
+ return d;
46
+ }
47
+
48
+ const pj = (v, d) => { try { return JSON.parse(v); } catch { return d; } };
49
+ const hostOf = (domain) => String(domain).replace(/^https?:\/\//i, '').replace(/\/.*$/, '').replace(/^www\./, '').toLowerCase();
50
+
51
+ /** Load the saved profile into niche.js. Called at start. */
52
+ export function loadProfile() {
53
+ const r = db().prepare("SELECT data FROM profile WHERE id = 'active'").get();
54
+ return setActiveProfile(r ? pj(r.data, null) : null);
55
+ }
56
+
57
+ export function saveProfile(p) {
58
+ const n = normalizeProfile(p);
59
+ db().prepare("INSERT INTO profile (id, domain, data, updated_at) VALUES ('active', ?, ?, ?) ON CONFLICT (id) DO UPDATE SET domain = excluded.domain, data = excluded.data, updated_at = excluded.updated_at")
60
+ .run(n.domain ?? null, JSON.stringify(n), now());
61
+ return setActiveProfile(n);
62
+ }
63
+
64
+ export function getProfile() {
65
+ const p = activeProfile();
66
+ const pages = db().prepare('SELECT COUNT(*) AS n FROM profile_pages WHERE domain = ?').get(hostOf(p.domain || '')).n;
67
+ return { ...p, indexed_pages: pages };
68
+ }
69
+
70
+ /** Replace a domain's indexed pages. */
71
+ export function indexPages(domain, pages) {
72
+ const d = db();
73
+ const host = hostOf(domain);
74
+ const old = d.prepare('SELECT url FROM profile_pages WHERE domain = ?').all(host).map((r) => r.url);
75
+ const delFts = d.prepare('DELETE FROM profile_pages_fts WHERE url = ?');
76
+ for (const u of old) delFts.run(u);
77
+ d.prepare('DELETE FROM profile_pages WHERE domain = ?').run(host);
78
+ const ins = d.prepare('INSERT OR REPLACE INTO profile_pages (url, domain, title, description, headings, text, via, fetched_at) VALUES (?,?,?,?,?,?,?,?)');
79
+ const fts = d.prepare('INSERT INTO profile_pages_fts (url, title, headings, text) VALUES (?,?,?,?)');
80
+ const t = now();
81
+ for (const p of pages) {
82
+ const headings = Array.isArray(p.headings) ? p.headings.slice(0, 30).map((x) => String(x).slice(0, 200)) : [];
83
+ const text = String(p.text || '').slice(0, 12_000);
84
+ ins.run(String(p.url).slice(0, 2000), host, String(p.title || '').slice(0, 200), String(p.description || '').slice(0, 500), JSON.stringify(headings), text, String(p.via || 'pushed').slice(0, 40), t);
85
+ fts.run(String(p.url).slice(0, 2000), String(p.title || ''), headings.join('\n'), text);
86
+ }
87
+ return pages.length;
88
+ }
89
+
90
+ export function pagesFor(domain, { withText = false } = {}) {
91
+ const cols = withText ? '*' : 'url, title, description, via, fetched_at, length(text) AS text_chars';
92
+ return db().prepare(`SELECT ${cols} FROM profile_pages WHERE domain = ? ORDER BY url`).all(hostOf(domain)).map((r) => (r.headings ? { ...r, headings: pj(r.headings, []) } : r));
93
+ }
94
+
95
+ /** Full-text search over the indexed site (FTS5 query built from plain words). */
96
+ export function searchPages(q, { limit = 10 } = {}) {
97
+ const words = String(q || '').toLowerCase().match(/[a-z0-9]{2,}/g) || [];
98
+ if (!words.length) return [];
99
+ const match = words.slice(0, 8).map((w) => `"${w}"`).join(' OR ');
100
+ return db().prepare(`SELECT url, title, snippet(profile_pages_fts, 3, '[', ']', ' ... ', 16) AS snippet, bm25(profile_pages_fts) AS rank
101
+ FROM profile_pages_fts WHERE profile_pages_fts MATCH ? ORDER BY rank LIMIT ?`).all(match, Math.min(Number(limit) || 10, 50));
102
+ }
103
+
104
+ /* ----------------------------------------------------------------- deriving -- */
105
+
106
+ const siteText = (pages) => pages.map((p) => [p.title, p.description, ...(p.headings || []), p.text].join('\n')).join('\n\n');
107
+
108
+ /** Niches from the library whose keywords the site uses, strongest first. */
109
+ export function libraryNiches(pages) {
110
+ const text = siteText(pages);
111
+ const head = pages.map((p) => [p.title, p.description, ...(p.headings || [])].join('\n')).join('\n');
112
+ const out = [];
113
+ for (const n of NICHE_LIBRARY) {
114
+ let hits = 0;
115
+ const used = [];
116
+ for (const k of n.keywords) {
117
+ const r = new RegExp(`(?<![\\w-])${k}(?![\\w-])`, 'gi');
118
+ const c = (text.match(r) || []).length + 2 * (head.match(r) || []).length;
119
+ if (c) { hits += c; used.push(k); }
120
+ }
121
+ if (hits >= 3) out.push({ ...n, hits, evidence: `site uses: ${used.slice(0, 6).join(', ')}` });
122
+ }
123
+ return out.sort((a, b) => b.hits - a.hits).map(({ hits, ...n }) => ({ ...n, enabled: true }));
124
+ }
125
+
126
+ const squash = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
127
+
128
+ /**
129
+ * A library niche with the same name as a model niche ("Cybersecurity" and
130
+ * "Cyber security") is folded into it, keywords added. Every other library
131
+ * niche the site supports is kept under its own name, so a well-known niche
132
+ * ("Software consulting", "Agentic engineering") is never renamed after a
133
+ * model's wording; two niches covering the same bid only add a second label.
134
+ */
135
+ export function mergeLibrary(modelNiches, lib) {
136
+ const out = modelNiches.map((n) => ({ ...n, keywords: [...n.keywords] }));
137
+ for (const l of lib) {
138
+ const twin = out.find((n) => { const a = squash(n.name); const b = squash(l.name); return a === b || (a.length > 6 && b.includes(a)) || (b.length > 6 && a.includes(b)); });
139
+ if (twin) {
140
+ twin.keywords = [...new Set([...twin.keywords, ...l.keywords])];
141
+ twin.libName = l.name;
142
+ } else out.push(l);
143
+ }
144
+ return out;
145
+ }
146
+
147
+ export const DerivedSchema = z.object({
148
+ company: z.string(),
149
+ summary: z.string(),
150
+ niches: z.array(z.object({
151
+ name: z.string(),
152
+ keywords: z.array(z.string()).default([]),
153
+ evidence: z.string().default(''),
154
+ })).default([]),
155
+ capabilities: z.array(z.string()).default([]),
156
+ naics: z.array(z.string()).default([]),
157
+ not_a_fit: z.array(z.string()).default([]),
158
+ });
159
+
160
+ const SYSTEM = `You read a company's own website and write its government-contracting niche profile.
161
+ Name 3 to 8 niches the company clearly sells (for example "Software consulting", "Agentic engineering", "Cybersecurity"), each with 4 to 12 short keywords or phrases a government solicitation TITLE would use for that work (lowercase, 1 to 4 words; "case management system", "penetration testing", "ai agents").
162
+ Only niches the pages actually support; quote the evidence briefly. List capabilities as short sentences, the 6-digit NAICS codes that fit (541511, 541512, 541519, 518210 and the like), and what the company should never bid on.
163
+ Answer with JSON only.`;
164
+
165
+ const clip = (s, n) => (s && s.length > n ? `${s.slice(0, n)}\n[...]` : s || '');
166
+
167
+ export function derivePrompt(domain, pages) {
168
+ const ranked = [...pages].sort((a, b) => (/(service|about|solution|capabilit|consult|agentic|\bai\b)/i.test(b.url) ? 1 : 0) - (/(service|about|solution|capabilit|consult|agentic|\bai\b)/i.test(a.url) ? 1 : 0));
169
+ let budget = 9000;
170
+ const parts = [];
171
+ for (const p of ranked) {
172
+ const block = `--- ${p.url}\n${p.title}\n${p.description || ''}\n${(p.headings || []).join(' | ')}\n${clip(p.text, 900)}`;
173
+ if (block.length > budget) break;
174
+ budget -= block.length;
175
+ parts.push(block);
176
+ }
177
+ return `Website: ${domain}\nPages read: ${pages.length}\n\n${parts.join('\n\n')}`;
178
+ }
179
+
180
+ /**
181
+ * Pages -> profile. A model answer is checked against the site text: a niche
182
+ * whose keywords never appear on the site is dropped. Library niches the site
183
+ * uses heavily are added when the model missed them.
184
+ */
185
+ export async function deriveProfile(domain, pages, { ai = makeAi() } = {}) {
186
+ const host = hostOf(domain);
187
+ const lib = libraryNiches(pages);
188
+ const text = siteText(pages).toLowerCase();
189
+ let derived = null;
190
+ let method = 'library';
191
+ let provider = null;
192
+ let aiError = null;
193
+ if (ai && pages.length) {
194
+ try {
195
+ const r = await ai.generateObject({
196
+ system: SYSTEM, user: derivePrompt(host, pages), schema: DerivedSchema, jsonSchema: z.toJSONSchema(DerivedSchema),
197
+ name: 'profile', feature: 'gov-contracts:profile', maxTokens: 2000, temperature: 0.2,
198
+ });
199
+ derived = r.object;
200
+ method = 'ai';
201
+ provider = r.provider;
202
+ } catch (e) {
203
+ aiError = String(e?.message || e).slice(0, 300);
204
+ }
205
+ }
206
+ let niches = lib;
207
+ if (derived) {
208
+ const grounded = derived.niches
209
+ .map((n) => {
210
+ const kws = [...new Set(n.keywords.map((k) => String(k).toLowerCase().trim()).filter((k) => k.length >= 2 && k.length <= 60))];
211
+ const onSite = kws.filter((k) => new RegExp(`(?<![\\w-])${keywordFragment(k)}(?![\\w-])`, 'i').test(text));
212
+ const libTwin = NICHE_LIBRARY.find((l) => l.name.toLowerCase() === n.name.toLowerCase());
213
+ return { name: n.name, keywords: [...new Set([...kws, ...(libTwin?.keywords || [])])], evidence: n.evidence, enabled: true, grounded: onSite.length };
214
+ })
215
+ .filter((n) => n.grounded > 0 && n.keywords.length)
216
+ .map(({ grounded, ...n }) => n);
217
+ niches = mergeLibrary(grounded, lib);
218
+ }
219
+ const libNaics = niches.flatMap((n) => NICHE_LIBRARY.find((l) => l.name === n.libName || l.name === n.name)?.naics || []);
220
+ const naics = [...new Set([...(derived?.naics || []).map((c) => String(c).replace(/\D/g, '')).filter((c) => /^\d{6}$/.test(c)), ...libNaics])];
221
+ return normalizeProfile({
222
+ company: derived?.company || pages.find((p) => p.title)?.title?.split(/[|\-:]/)[0]?.trim() || host,
223
+ domain: host,
224
+ summary: derived?.summary || pages.find((p) => p.description)?.description || `Read from ${host}.`,
225
+ capabilities: derived?.capabilities?.length ? derived.capabilities : niches.map((n) => n.name),
226
+ niches: niches.length ? niches : DEFAULT_PROFILE.niches,
227
+ negative_keywords: BASE_NEGATIVE,
228
+ naics: naics.length ? naics : DEFAULT_PROFILE.naics,
229
+ not_a_fit: derived?.not_a_fit?.length ? derived.not_a_fit : DEFAULT_PROFILE.not_a_fit,
230
+ source: `site:${host}`,
231
+ method: method === 'ai' ? `ai${provider ? `:${provider}` : ''}` : 'library',
232
+ crawled_at: now(),
233
+ pages: pages.length,
234
+ ...(aiError ? { ai_error: aiError } : {}),
235
+ });
236
+ }
237
+
238
+ /* --------------------------------------------------------------- re-screen -- */
239
+
240
+ /**
241
+ * Score every open solicitation against the active profile. Bids that left
242
+ * the niche stop at 'skipped' (if not read yet) and their open bid/no-bid
243
+ * card is hidden by the niche filter; bids that entered it go back to 'new'
244
+ * so they are read and scored. Scored, drafted and resolved work is kept.
245
+ */
246
+ export function rescreen(profile = activeProfile()) {
247
+ compile(profile);
248
+ const d = openDb();
249
+ const rows = d.prepare("SELECT id, title, description, naics, status FROM solicitations WHERE due_at IS NULL OR due_at >= ?").all(now().slice(0, 10));
250
+ const upd = d.prepare('UPDATE solicitations SET prefilter = ?, niche_score = ?, niches = ?, status = ? WHERE id = ?');
251
+ const counts = { checked: rows.length, in_niche: 0, entered: 0, left: 0 };
252
+ d.exec('BEGIN');
253
+ try {
254
+ for (const r of rows) {
255
+ const m = nicheMatch(r, profile);
256
+ let status = r.status;
257
+ if (m.score > 0 && r.status === 'skipped') { status = 'new'; counts.entered++; }
258
+ else if (m.score === 0 && (r.status === 'new' || r.status === 'read')) { status = 'skipped'; counts.left++; }
259
+ if (m.score > 0) counts.in_niche++;
260
+ upd.run(m.score, m.score, JSON.stringify(m.niches), status, r.id);
261
+ }
262
+ d.exec('COMMIT');
263
+ } catch (e) {
264
+ d.exec('ROLLBACK');
265
+ throw e;
266
+ }
267
+ logRun('rescreen', true, counts);
268
+ return counts;
269
+ }
270
+
271
+ /* ----------------------------------------------------------------- the job -- */
272
+
273
+ let running = null;
274
+ export const crawlRunning = () => running;
275
+
276
+ /** Crawl a domain, index it, derive the profile, make it active, re-screen. One at a time. */
277
+ export async function buildProfile(domain, { maxPages, fetchPage, fetchSitemap, ai } = {}) {
278
+ if (running) return { status: 'already running', domain: running };
279
+ const host = hostOf(domain || activeProfile().domain || DEFAULT_PROFILE.domain);
280
+ running = host;
281
+ try {
282
+ const crawl = await crawlSite(host, { maxPages, ...(fetchPage ? { fetchPage } : {}), ...(fetchSitemap ? { fetchSitemap } : {}) });
283
+ if (!crawl.pages.length) throw new Error(`no readable pages on ${host}: ${crawl.errors.map((e) => e.error).slice(0, 3).join('; ') || 'nothing fetched'}`);
284
+ return await applyPages(host, crawl.pages, { ai, crawl });
285
+ } catch (e) {
286
+ logRun('profile', false, String(e?.message || e).slice(0, 300));
287
+ throw e;
288
+ } finally {
289
+ running = null;
290
+ }
291
+ }
292
+
293
+ /** Pages read elsewhere (the CLI's local c0mpute spider) -> index, derive, activate, re-screen. */
294
+ export async function applyPages(domain, pages, { ai = makeAi(), crawl = null } = {}) {
295
+ const host = hostOf(domain);
296
+ indexPages(host, pages);
297
+ const prev = activeProfile();
298
+ const derived = await deriveProfile(host, pages, { ai });
299
+ // Operator edits survive a re-crawl: niches they switched off stay off.
300
+ const off = new Set(prev.niches.filter((n) => n.enabled === false).map((n) => n.name.toLowerCase()));
301
+ derived.niches = derived.niches.map((n) => (off.has(n.name.toLowerCase()) ? { ...n, enabled: false } : n));
302
+ const profile = saveProfile(derived);
303
+ const screened = rescreen(profile);
304
+ const via = crawl?.via || pages.reduce((a, p) => ({ ...a, [p.via || 'pushed']: (a[p.via || 'pushed'] || 0) + 1 }), {});
305
+ const result = { domain: host, pages: pages.length, via, method: profile.method, niches: profile.niches.map((n) => n.name), screened, notes: crawl?.notes || [] };
306
+ logRun('profile', true, result);
307
+ return result;
308
+ }
package/src/propose.js ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Proposal drafts and the human queue.
3
+ *
4
+ * A draft has a cover letter, a technical approach mapped to the RFP's
5
+ * requirements, a pricing SECTION with every number left blank, the required
6
+ * forms checklist and a compliance matrix. It is never sent anywhere. Each
7
+ * draft queues the cards a person must work: price it, sign/certify the forms,
8
+ * register on the buyer's portal if not yet done, and finally review and
9
+ * submit it themselves.
10
+ */
11
+ import { z } from 'zod';
12
+ import { DRAFT_BANNER } from './safety.js';
13
+ import { PROFILE, fitPrompt } from './fit.js';
14
+ import { latestProposal, queueIntervention, saveProposal, setSolicitation } from './store.js';
15
+
16
+ export const ProposalSchema = z.object({
17
+ cover_letter: z.string(),
18
+ executive_summary: z.string(),
19
+ technical_approach: z.string(),
20
+ management_and_staffing: z.string().default(''),
21
+ schedule: z.string().default(''),
22
+ compliance_matrix: z.array(z.object({ requirement: z.string(), response: z.string(), section: z.string().default('') })).default([]),
23
+ forms_checklist: z.array(z.object({ form: z.string(), action: z.enum(['fill', 'sign', 'notarize', 'certify', 'attach', 'register']).default('fill'), note: z.string().default('') })).default([]),
24
+ pricing_structure: z.array(z.object({ item: z.string(), unit: z.string().default('') })).default([]),
25
+ questions_for_buyer: z.array(z.string()).default([]),
26
+ });
27
+
28
+ const system = () => `You write government proposal DRAFTS for ${PROFILE.company} for a person to review. ${PROFILE.summary}
29
+ Rules:
30
+ - Respond to the buyer's actual requirements; reuse their section names and requirement wording in the compliance matrix.
31
+ - NEVER state a price, rate, discount or total. Pricing is only the structure (line items and units); a person fills in numbers.
32
+ - NEVER claim certifications, past contracts, clearances, insurance or staff that are not given to you. Where the RFP needs them, write [TO CONFIRM: ...].
33
+ - NEVER sign, certify or attest. List every form the buyer requires in forms_checklist with the action a person must take.
34
+ - The due date is when the PROPOSAL is due, not when work is delivered. Never promise a delivery date; schedules are relative to award (\"week 1-4 after award\").
35
+ - Plain, specific language. No marketing filler. No em dashes.
36
+ Answer with JSON only.`;
37
+
38
+ /** Portals a bidder must be registered on to bid, by source and buyer. */
39
+ export function vendorPortals(sol) {
40
+ if (sol.source === 'sam' || sol.level === 'federal') {
41
+ return [{ key: 'sam.gov', name: 'SAM.gov entity registration (UEI)', url: 'https://sam.gov/entity-registration', steps: ['Sign in to SAM.gov with Login.gov.', 'Register the entity (Profullstack, Inc.) to get a Unique Entity ID; choose "all awards".', 'Add NAICS 541511, 541512, 541519, 518210 and the small-business representations.', 'Registration is free; it takes 7-10 business days to activate. Record the UEI and CAGE code here when done.'] }];
42
+ }
43
+ if (sol.source === 'lacounty') {
44
+ return [{ key: 'lacounty', name: 'LA County vendor registration (WebVen)', url: 'https://camisvr.co.la.ca.us/WebVen/', steps: ['Open WebVen and register Profullstack, Inc. as a vendor.', 'Add the commodity codes for software, IT services and computer maintenance.', 'Record the vendor number here when done.'] }];
45
+ }
46
+ if (sol.level === 'state' && sol.region === 'CA') {
47
+ return [{ key: 'caleprocure', name: 'Cal eProcure supplier registration (Supplier ID)', url: 'https://caleprocure.ca.gov/pages/index.aspx', steps: ['Open Cal eProcure and register as a supplier.', 'Optional: apply for Small Business (SB/DVBE) certification; it scores bid preference.', 'Record the Supplier ID here when done.'] }];
48
+ }
49
+ const buyer = sol.agency || 'the buyer';
50
+ return [{ key: `buyer:${buyer.toLowerCase()}`, name: `${buyer} vendor portal`, url: null, steps: [`Find ${buyer}'s procurement page (search "${buyer} bid opportunities").`, 'Register as a vendor there (most cities use PlanetBids, OpenGov, Bonfire or BidNet).', 'Download the solicitation documents and attach them on this card (paste the link in the note).'] }];
51
+ }
52
+
53
+ const md = (s) => String(s || '').trim();
54
+
55
+ export function toMarkdown(sol, p, { method } = {}) {
56
+ const lines = [
57
+ `> ${DRAFT_BANNER}`,
58
+ '',
59
+ `# Proposal draft: ${sol.title}`,
60
+ '',
61
+ `- Buyer: ${sol.agency || 'n/a'}`,
62
+ `- Solicitation: ${sol.number || 'n/a'}${sol.url ? ` (${sol.url})` : ''}`,
63
+ `- Due: ${sol.due_at || 'n/a'}`,
64
+ `- Prepared by: ${method === 'template' ? 'template (no AI answer)' : method === 'partial' ? 'AI draft, some sections template' : 'AI draft'} for ${PROFILE.company}`,
65
+ '',
66
+ '## Cover letter',
67
+ '',
68
+ md(p.cover_letter),
69
+ '',
70
+ '## Executive summary',
71
+ '',
72
+ md(p.executive_summary),
73
+ '',
74
+ '## Technical approach',
75
+ '',
76
+ md(p.technical_approach),
77
+ ];
78
+ if (md(p.management_and_staffing)) lines.push('', '## Management and staffing', '', md(p.management_and_staffing));
79
+ if (md(p.schedule)) lines.push('', '## Schedule', '', md(p.schedule));
80
+ lines.push('', '## Pricing (a person sets every number)', '', '| Item | Unit | Price |', '|---|---|---|');
81
+ for (const r of p.pricing_structure?.length ? p.pricing_structure : [{ item: 'Total firm-fixed price', unit: 'lot' }]) lines.push(`| ${r.item} | ${r.unit || ''} | [SET BY A PERSON] |`);
82
+ lines.push('', '## Required forms checklist', '');
83
+ if (p.forms_checklist?.length) for (const f of p.forms_checklist) lines.push(`- [ ] ${f.form} (${f.action}, by a person)${f.note ? `: ${f.note}` : ''}`);
84
+ else lines.push('- [ ] Open the solicitation documents and list every required form here (none were named in the text the system could read).');
85
+ if (p.compliance_matrix?.length) {
86
+ lines.push('', '## Compliance matrix', '', '| Requirement | Response | Section |', '|---|---|---|');
87
+ for (const r of p.compliance_matrix) lines.push(`| ${r.requirement.replace(/\|/g, '/')} | ${r.response.replace(/\|/g, '/')} | ${r.section || ''} |`);
88
+ }
89
+ if (p.questions_for_buyer?.length) {
90
+ lines.push('', '## Questions for the buyer (for a person to send, if wanted)', '');
91
+ for (const q of p.questions_for_buyer) lines.push(`- ${q}`);
92
+ }
93
+ return lines.join('\n') + '\n';
94
+ }
95
+
96
+ /** A skeleton when no model answered, so the card still exists and a person can write it. */
97
+ export function templateProposal(sol, fit) {
98
+ return {
99
+ cover_letter: `[TO WRITE] Letter to ${sol.agency || 'the buyer'} for ${sol.number || sol.title}: who we are, why we fit, point of contact.`,
100
+ executive_summary: '[TO WRITE] Two or three sentences: the buyer\'s problem, our approach, why us.',
101
+ technical_approach: '[TO WRITE] Respond to each requirement in the solicitation, in its own order and wording.',
102
+ management_and_staffing: '',
103
+ schedule: '',
104
+ compliance_matrix: (fit?.requirements || []).map((r) => ({ requirement: r, response: '[TO WRITE]', section: '' })),
105
+ forms_checklist: [],
106
+ pricing_structure: [],
107
+ questions_for_buyer: [],
108
+ };
109
+ }
110
+
111
+ /** The draft in three small parts: a 4B model answers each inside its timeout, and a part that fails falls back alone. */
112
+ const PARTS = [
113
+ {
114
+ name: 'letter',
115
+ ask: 'Write cover_letter (to the buyer, under 250 words, signature block left as [NAME, TITLE]) and executive_summary (under 150 words).',
116
+ schema: ProposalSchema.pick({ cover_letter: true, executive_summary: true }),
117
+ maxTokens: 1500,
118
+ },
119
+ {
120
+ name: 'approach',
121
+ ask: 'Write technical_approach (markdown, one subsection per buyer requirement, in their order and wording, under 700 words), management_and_staffing and schedule (each under 150 words; roles not names).',
122
+ schema: ProposalSchema.pick({ technical_approach: true, management_and_staffing: true, schedule: true }),
123
+ maxTokens: 2500,
124
+ },
125
+ {
126
+ name: 'compliance',
127
+ ask: 'Write compliance_matrix (each mandatory requirement and where the proposal answers it), forms_checklist (ONLY forms named in the documents above; none if none are named), pricing_structure (line items and units, NO prices) and questions_for_buyer.',
128
+ schema: ProposalSchema.pick({ compliance_matrix: true, forms_checklist: true, pricing_structure: true, questions_for_buyer: true }),
129
+ maxTokens: 2000,
130
+ },
131
+ ];
132
+
133
+ /** Keep a form only if its name (2+ words of it) shows up in what was actually read. Models invent "Form 1..6". */
134
+ export function formsInText(forms, docs) {
135
+ const norm = (t) => ` ${String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;
136
+ const text = norm(docs.map((d) => d.text || '').join(' '));
137
+ return forms.filter((f) => {
138
+ const name = norm(String(f.form || f).replace(/^\s*(rfp|rfq|exhibit|attachment|appendix)?[\s-]*(form)?[\s-]*[a-z]?\d+[a-z]?\s*[:.)-]\s*/i, ''));
139
+ return name.trim().length >= 4 && text.includes(name);
140
+ });
141
+ }
142
+
143
+ /** Draft a proposal for a scored solicitation and queue its human cards. */
144
+ export async function draftProposal(sol, docs, { ai, timeoutMs } = {}) {
145
+ const fit = sol.fit || {};
146
+ const base = templateProposal(sol, fit);
147
+ const body = { ...base };
148
+ const used = [];
149
+ if (ai) {
150
+ const context = `${fitPrompt(sol, docs)}\n\nRequirements found: ${JSON.stringify(fit.requirements || []).slice(0, 1500)}`;
151
+ for (const part of PARTS) {
152
+ try {
153
+ const r = await ai.generateObject({
154
+ system: system(),
155
+ user: `${context}\n\n${part.ask}`,
156
+ schema: part.schema,
157
+ jsonSchema: z.toJSONSchema(part.schema),
158
+ name: `proposal_${part.name}`,
159
+ feature: `gov-contracts:proposal:${part.name}`,
160
+ maxTokens: part.maxTokens,
161
+ temperature: 0.3,
162
+ ...(timeoutMs ? { timeoutMs } : {}),
163
+ });
164
+ Object.assign(body, r.object);
165
+ used.push({ part: part.name, provider: r.provider, model: r.model });
166
+ } catch (e) {
167
+ console.error(`proposal ${part.name} failed`, sol.id, String(e?.message || e).slice(0, 200));
168
+ }
169
+ }
170
+ }
171
+ const method = used.length === PARTS.length ? 'ai' : used.length ? 'partial' : 'template';
172
+ // Forms: only ones named in what we read (the model's and the fit step's), else a reminder to read the documents.
173
+ const named = formsInText([...(body.forms_checklist || []), ...(fit.forms || []).map((f) => ({ form: f, action: 'fill', note: '' }))], docs);
174
+ const seen = new Set();
175
+ body.forms_checklist = named.filter((f) => !seen.has(f.form.toLowerCase()) && seen.add(f.form.toLowerCase()));
176
+ const markdown = toMarkdown(sol, body, { method });
177
+ const provider = [...new Set(used.map((u) => u.provider))].join('+') || null;
178
+ const model = [...new Set(used.map((u) => u.model))].join('+') || null;
179
+ const saved = saveProposal(sol.id, { body: { ...body, method, parts: used }, markdown, provider, model });
180
+ setSolicitation(sol.id, { status: 'drafted' });
181
+ queueCards(sol, { id: saved.id, body, markdown });
182
+ return { ...saved, method, provider, model };
183
+ }
184
+
185
+ const priorityFor = (sol) => {
186
+ const days = sol.due_at ? (Date.parse(sol.due_at) - Date.now()) / 86400_000 : 60;
187
+ return Math.round(Math.min(100, (sol.fit_score || 0) * 0.7 + Math.max(0, 30 - days)));
188
+ };
189
+
190
+ /** The cards a person works for one draft. Deduped by key, so re-drafting updates them. */
191
+ export function queueCards(sol, proposal) {
192
+ const pri = priorityFor(sol);
193
+ const where = sol.url ? `the solicitation page (${sol.url})` : `${sol.agency}'s procurement page`;
194
+ const portals = vendorPortals(sol);
195
+ for (const p of portals) {
196
+ queueIntervention({
197
+ key: `register_vendor:${p.key}`,
198
+ kind: 'register_vendor',
199
+ solicitation_id: sol.id,
200
+ title: `Register as a vendor: ${p.name}`,
201
+ body: `Bidding on "${sol.title}" (and others from this buyer) needs a vendor account. The system never registers or signs anything itself.\n\n${p.steps.map((s, i) => `${i + 1}. ${s}`).join('\n')}`,
202
+ open_url: p.url,
203
+ priority: pri + 5,
204
+ due_at: sol.due_at,
205
+ });
206
+ }
207
+ queueIntervention({
208
+ key: `set_price:${sol.id}`,
209
+ kind: 'set_price',
210
+ solicitation_id: sol.id,
211
+ proposal_id: proposal.id,
212
+ title: `Set the price: ${sol.title}`,
213
+ body: `The draft leaves every number blank. Decide the price for each line below and put it in the proposal before submitting.\n\n${(proposal.body.pricing_structure?.length ? proposal.body.pricing_structure : [{ item: 'Total firm-fixed price', unit: 'lot' }]).map((r, i) => `${i + 1}. ${r.item}${r.unit ? ` (${r.unit})` : ''}`).join('\n')}`,
214
+ open_url: sol.url,
215
+ priority: pri,
216
+ due_at: sol.due_at,
217
+ });
218
+ const forms = proposal.body.forms_checklist || [];
219
+ if (forms.length) {
220
+ queueIntervention({
221
+ key: `sign_or_certify:${sol.id}`,
222
+ kind: 'sign_or_certify',
223
+ solicitation_id: sol.id,
224
+ proposal_id: proposal.id,
225
+ title: `Fill, sign or certify ${forms.length} form${forms.length === 1 ? '' : 's'}: ${sol.title}`,
226
+ body: `Only an authorized person at the bidder can complete these.\n\n${forms.map((f, i) => `${i + 1}. ${f.form}: ${f.action}${f.note ? ` (${f.note})` : ''}`).join('\n')}`,
227
+ open_url: sol.url,
228
+ priority: pri,
229
+ due_at: sol.due_at,
230
+ });
231
+ }
232
+ queueIntervention({
233
+ key: `submit_proposal:${sol.id}`,
234
+ kind: 'submit_proposal',
235
+ solicitation_id: sol.id,
236
+ proposal_id: proposal.id,
237
+ title: `Review and submit (by hand): ${sol.title}`,
238
+ body: `Fit ${sol.fit_score ?? '?'}/100. ${sol.fit?.summary || ''}\n\n1. Read the draft (Copy below, or Proposal).\n2. Fix every [TO CONFIRM] / [TO WRITE], set the prices, complete the forms.\n3. Submit it yourself on ${where} before ${sol.due_at || 'the deadline'}, following the buyer's instructions.\n4. Mark done with the confirmation number. Dismiss if we are not bidding.\n\nThe system never submits, emails the buyer or certifies anything.`,
239
+ open_url: sol.url,
240
+ copy_text: proposal.markdown,
241
+ priority: pri + 10,
242
+ due_at: sol.due_at,
243
+ });
244
+ }
245
+
246
+ /** A "maybe" fit: a person decides whether it is worth a draft. */
247
+ export function queueDecision(sol) {
248
+ queueIntervention({
249
+ key: `decide_bid:${sol.id}`,
250
+ kind: 'decide_bid',
251
+ solicitation_id: sol.id,
252
+ title: `Worth a bid? ${sol.title}`,
253
+ body: `Fit ${sol.fit_score ?? '?'}/100 (${sol.fit?.verdict || 'maybe'}). ${sol.fit?.summary || ''}\n\nRisks: ${(sol.fit?.risks || []).join('; ') || 'none listed'}\n\n1. Open the solicitation.\n2. "Draft it" queues a proposal draft; Dismiss skips it.`,
254
+ open_url: sol.url,
255
+ priority: Math.round((sol.fit_score || 0) * 0.6),
256
+ due_at: sol.due_at,
257
+ });
258
+ }
259
+
260
+ export { latestProposal };
package/src/safety.js ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The hard line. gov-contracts automates everything UP TO the submit button and
3
+ * stops there. Submitting a bid, registering a vendor account, signing or
4
+ * certifying a form, setting a price and writing to an agency are legal and
5
+ * business commitments for the bidder, so they are only ever intervention
6
+ * cards a person works by hand.
7
+ *
8
+ * There is deliberately no code here (or anywhere in this package) that can do
9
+ * any of those things: no mail transport, no form posting to an agency, no
10
+ * portal login. test/safety.test.js scans the source to keep it that way.
11
+ */
12
+
13
+ /** Actions the system must never take on its own. Each one maps to a card kind. */
14
+ export const HUMAN_ONLY = Object.freeze({
15
+ submit_proposal: 'Submitting a proposal or bid to a government buyer',
16
+ register_vendor: 'Registering or updating a vendor/supplier account on a procurement portal (SAM.gov UEI, Cal eProcure, PlanetBids, county portals)',
17
+ sign_or_certify: 'Signing, notarizing or certifying any form, representation or affidavit',
18
+ set_price: 'Setting the price, rates or any number the bidder is bound by',
19
+ contact_agency: 'Emailing, calling or messaging an agency, a contracting officer or any third party',
20
+ decide_bid: 'Deciding to bid (a business decision)',
21
+ });
22
+
23
+ /** Hosts the system may READ from. Nothing is ever written to them. */
24
+ export const READ_ONLY_HOSTS = Object.freeze([
25
+ 'sam.gov',
26
+ 'api.sam.gov',
27
+ 'falextracts.s3.amazonaws.com',
28
+ 'iae-fbo-attachments.s3.amazonaws.com',
29
+ 'camisvr.co.la.ca.us',
30
+ 'mcp.profullstack.com',
31
+ 'pit.world',
32
+ ]);
33
+
34
+ /** Proposal states. `submitted` is only ever set by a person marking a card done. */
35
+ export const PROPOSAL_STATES = ['draft', 'approved', 'submitted_by_human', 'declined'];
36
+
37
+ /** Every drafted proposal carries this banner until a person approves it. */
38
+ export const DRAFT_BANNER =
39
+ 'DRAFT prepared by software for human review. Not submitted. Nothing here is a commitment, price or certification until a person at the bidder reviews, completes and submits it themselves.';
40
+
41
+ /** Refuse anything that looks like an attempt to automate a human-only step. */
42
+ export function assertHumanOnly(action) {
43
+ if (Object.hasOwn(HUMAN_ONLY, action)) {
44
+ const e = new Error(`${HUMAN_ONLY[action]} is a human step. gov-contracts queues it as an intervention card and never does it itself.`);
45
+ e.code = 'human_only';
46
+ throw e;
47
+ }
48
+ }
package/src/server.js ADDED
@@ -0,0 +1,17 @@
1
+ import { serve } from '@hono/node-server';
2
+ import { app } from './app.js';
3
+ import { bootProfile } from './pipeline.js';
4
+ import { startDaemon, getDaemon } from './pipeline.js';
5
+
6
+ const port = Number(process.env.PORT || 8080);
7
+ const hostname = process.env.HOST || '0.0.0.0';
8
+
9
+ bootProfile();
10
+ serve({ fetch: app.fetch, port, hostname }, () => {
11
+ console.log(`gov-contracts listening on http://${hostname}:${port}`);
12
+ startDaemon();
13
+ });
14
+
15
+ const stop = () => Promise.resolve(getDaemon()?.stop()).finally(() => process.exit(0));
16
+ process.on('SIGTERM', stop);
17
+ process.on('SIGINT', stop);
package/src/service.js ADDED
@@ -0,0 +1,27 @@
1
+ /** Shared by the HTTP API, pages and MCP. */
2
+ import { draftOne } from './pipeline.js';
3
+ import { getSolicitation, setSolicitation } from './store.js';
4
+
5
+ /** What anyone may see. Fit scores and drafts are the bidder's own business. */
6
+ export function publicSolicitation(s, isOperator = false) {
7
+ if (!s) return null;
8
+ const { fit, fit_score, prefilter, error, ...rest } = s;
9
+ return isOperator ? { ...rest, prefilter, fit_score, fit, error } : rest;
10
+ }
11
+
12
+ const drafting = new Set();
13
+
14
+ /** Draft in the background (a model can take minutes); the cards appear when it finishes. */
15
+ export function startDraft(id) {
16
+ const s = getSolicitation(id);
17
+ if (!s) throw new Error('not found');
18
+ if (drafting.has(id)) return { id, status: 'already drafting' };
19
+ drafting.add(id);
20
+ setSolicitation(id, { status: s.status === 'skipped' ? 'read' : s.status });
21
+ draftOne(getSolicitation(id))
22
+ .catch((e) => console.error('draft failed', id, String(e?.message || e).slice(0, 200)))
23
+ .finally(() => drafting.delete(id));
24
+ return { id, status: 'drafting', note: 'The proposal and its queue cards appear when the draft finishes (usually 1-3 minutes).' };
25
+ }
26
+
27
+ export const isDrafting = (id) => drafting.has(id);