@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/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /** @profullstack/gov-contracts: library entry. The hosted app is ./server (src/app.js). */
2
+ export { HUMAN_ONLY, READ_ONLY_HOSTS, DRAFT_BANNER, assertHumanOnly } from './safety.js';
3
+ export { PROFILE, prefilter, scoreFit, keywordFit, FitSchema } from './fit.js';
4
+ export { ADAPTERS, listSources, registry, sam, lacounty, digest } from './sources/index.js';
5
+ export { parseDigest, parseMyGovWatch } from './sources/digest.js';
6
+ export { draftProposal, toMarkdown, vendorPortals, ProposalSchema } from './propose.js';
7
+ export { ingestSource, ingestDigest, workTick, startDaemon } from './pipeline.js';
8
+ export { makeAi, aiStatus } from './ai.js';
9
+ export { DEFAULT_PROFILE, NICHE_LIBRARY, nicheMatch, normalizeProfile, activeProfile, setActiveProfile } from './niche.js';
10
+ export { crawlSite, makePageFetcher, extractLinks, parseSitemap, pageSummary } from './spider.js';
11
+ export { buildProfile, applyPages, deriveProfile, getProfile, saveProfile, rescreen, searchPages } from './profile.js';
12
+ export { VERSION } from './version.js';
package/src/mcp.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * MCP server (streamable HTTP, stateless). Public tools read solicitations and
3
+ * sources; operator tools (Bearer OPERATOR_API_KEY on the connection) work the
4
+ * queue. There is no tool that submits, registers, signs, prices or emails:
5
+ * resolve_intervention only RECORDS what a person did.
6
+ */
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
9
+ import { z } from 'zod';
10
+ import { bearerIsOperator } from './auth.js';
11
+ import { listSources } from './sources/index.js';
12
+ import { publicSolicitation, startDraft } from './service.js';
13
+ import { ingestDigest } from './pipeline.js';
14
+ import { applyPages, buildProfile, crawlRunning, getProfile, rescreen, saveProfile, searchPages } from './profile.js';
15
+ import {
16
+ documentsFor, getProposal, getSolicitation, latestProposal, listInterventions, nicheCounts, resolveIntervention, searchSolicitations, stats,
17
+ } from './store.js';
18
+ import { VERSION } from './version.js';
19
+
20
+ const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
21
+ const fail = (msg) => ({ isError: true, content: [{ type: 'text', text: msg }] });
22
+ const NEED_KEY = 'Operator tool: send the gov-contracts operator key as "Authorization: Bearer <key>" on the MCP connection.';
23
+
24
+ export const TOOL_NAMES = [
25
+ 'search_solicitations', 'get_solicitation', 'list_sources', 'stats',
26
+ 'list_interventions', 'get_proposal', 'resolve_intervention', 'draft_proposal', 'ingest_digest',
27
+ 'get_profile', 'search_profile_pages', 'crawl_profile', 'update_profile',
28
+ ];
29
+
30
+ export function buildMcpServer({ isOperator = false } = {}) {
31
+ const server = new McpServer(
32
+ { name: 'gov.procurement', version: VERSION },
33
+ {
34
+ instructions:
35
+ 'gov.procurement finds government contract opportunities (SAM.gov, LA County, forwarded bid digests), reads the RFP, scores fit for Profullstack and drafts proposals. ' +
36
+ 'It never submits a bid, registers a vendor account, signs or certifies, sets a price or contacts an agency: those are intervention cards a person works. ' +
37
+ 'Typical loop: search_solicitations -> get_solicitation -> (operator) list_interventions -> get_proposal -> a person submits -> resolve_intervention to record it.',
38
+ },
39
+ );
40
+ const op = (fn) => async (args) => {
41
+ if (!isOperator) return fail(NEED_KEY);
42
+ try { return text(await fn(args)); } catch (e) { return fail(String(e?.message || e)); }
43
+ };
44
+ const pub = (fn) => async (args) => {
45
+ try { return text(await fn(args)); } catch (e) { return fail(String(e?.message || e)); }
46
+ };
47
+
48
+ server.registerTool('search_solicitations', {
49
+ description: 'Open government solicitations. Filter by keyword, level (federal|state|county|city), source (sam|lacounty|digest) and niche ("in" = any of our niches, the default; a niche name from get_profile; "out"; "all"). Ordered by fit (operators) or due date.',
50
+ inputSchema: {
51
+ q: z.string().optional(), level: z.enum(['federal', 'state', 'county', 'city']).optional(), source: z.enum(['sam', 'lacounty', 'digest']).optional(),
52
+ niche: z.string().max(80).optional(), order: z.enum(['fit', 'due', 'new', 'niche']).optional(), limit: z.number().int().min(1).max(100).optional(),
53
+ },
54
+ annotations: { readOnlyHint: true },
55
+ }, pub(({ q, level, source, niche, order, limit }) => searchSolicitations({ q, level, source, niche: niche || 'in', order: order || (isOperator ? 'fit' : 'due'), limit: limit || 25 }).map((s) => publicSolicitation(s, isOperator))));
56
+
57
+ server.registerTool('get_solicitation', {
58
+ description: 'One solicitation by id (e.g. "sam:<notice id>", "lacounty:50629"), with the documents read for it.',
59
+ inputSchema: { id: z.string() },
60
+ annotations: { readOnlyHint: true },
61
+ }, pub(({ id }) => {
62
+ const s = getSolicitation(id);
63
+ if (!s) throw new Error('not found');
64
+ const p = isOperator ? latestProposal(id) : null;
65
+ return { ...publicSolicitation(s, isOperator), documents: documentsFor(id, { withText: false }), ...(p ? { proposal: { id: p.id, version: p.version, status: p.status } } : {}) };
66
+ }));
67
+
68
+ server.registerTool('list_sources', {
69
+ description: "Where contract opportunities come from: Datamart's contracts registry joined with the sources gov-contracts reads.",
70
+ inputSchema: {},
71
+ annotations: { readOnlyHint: true },
72
+ }, pub(() => listSources()));
73
+
74
+ server.registerTool('stats', { description: 'Counts by status, source and level, and the last run of each job.', inputSchema: {}, annotations: { readOnlyHint: true } }, pub(() => stats()));
75
+
76
+ server.registerTool('list_interventions', {
77
+ description: 'Operator: the human intervention queue (cards a person must work).',
78
+ inputSchema: { status: z.enum(['open', 'done', 'dismissed', 'all']).optional(), kind: z.string().optional(), niche: z.string().max(80).optional().describe('"in" (default), a niche name, "out" or "all"') },
79
+ annotations: { readOnlyHint: true },
80
+ }, op(({ status, kind, niche }) => listInterventions({ status: status || 'open', kind, niche: niche || 'in' }).map(({ copy_text, ...iv }) => ({ ...iv, has_copy_text: !!copy_text }))));
81
+
82
+ server.registerTool('get_proposal', {
83
+ description: 'Operator: a proposal draft (markdown) by proposal id, or the latest for a solicitation id.',
84
+ inputSchema: { id: z.string() },
85
+ annotations: { readOnlyHint: true },
86
+ }, op(({ id }) => {
87
+ const p = getProposal(id) || latestProposal(id);
88
+ if (!p) throw new Error('not found');
89
+ return { id: p.id, solicitation_id: p.solicitation_id, version: p.version, status: p.status, markdown: p.markdown };
90
+ }));
91
+
92
+ server.registerTool('resolve_intervention', {
93
+ description: 'Operator: record that a PERSON did (done) or skipped (dismissed) a card, with a note (confirmation number, UEI, reason). Does not perform the action.',
94
+ inputSchema: { id: z.string(), status: z.enum(['done', 'dismissed', 'open']), note: z.string().max(2000).optional() },
95
+ }, op(({ id, status, note }) => {
96
+ const r = resolveIntervention(id, { status, note, by: 'mcp operator key' });
97
+ if (!r) throw new Error('not found');
98
+ return r;
99
+ }));
100
+
101
+ server.registerTool('draft_proposal', {
102
+ description: 'Operator: (re)draft a proposal for a solicitation in the background; its cards appear in the queue when done.',
103
+ inputSchema: { id: z.string() },
104
+ }, op(({ id }) => startDraft(id)));
105
+
106
+ server.registerTool('ingest_digest', {
107
+ description: 'Operator: add every solicitation listed in a forwarded bid digest (plain text). Links in it are ignored.',
108
+ inputSchema: { text: z.string().max(200_000) },
109
+ }, op(({ text: body }) => ingestDigest(body)));
110
+
111
+ server.registerTool('get_profile', {
112
+ description: "The bidder's niche profile, read from its own website: niches with keywords, NAICS codes, what is never a fit, and how many open bids fall in each niche. Bids are filtered by it.",
113
+ inputSchema: {},
114
+ annotations: { readOnlyHint: true },
115
+ }, pub(() => ({ ...getProfile(), crawling: crawlRunning(), niche_counts: nicheCounts() })));
116
+
117
+ server.registerTool('search_profile_pages', {
118
+ description: "Full-text search over the bidder's indexed website pages (evidence for a capability claim in a proposal).",
119
+ inputSchema: { q: z.string().max(200), limit: z.number().int().min(1).max(50).optional() },
120
+ annotations: { readOnlyHint: true },
121
+ }, pub(({ q, limit }) => searchPages(q, { limit })));
122
+
123
+ server.registerTool('crawl_profile', {
124
+ description: "Operator: re-read a website (c0mpute crawl.fetch first, direct fallback), derive the niches with a model and re-screen every open bid. Runs in the background; poll get_profile. Pass pages instead to use pages you already read.",
125
+ inputSchema: {
126
+ domain: z.string().max(253),
127
+ max_pages: z.number().int().min(1).max(200).optional(),
128
+ pages: z.array(z.object({ url: z.string(), title: z.string().optional(), description: z.string().optional(), headings: z.array(z.string()).optional(), text: z.string().optional(), via: z.string().optional() })).max(200).optional(),
129
+ },
130
+ }, op(async ({ domain, max_pages, pages }) => {
131
+ if (pages?.length) return applyPages(domain, pages);
132
+ if (crawlRunning()) return { status: 'already running', domain: crawlRunning() };
133
+ buildProfile(domain, { maxPages: max_pages }).catch((e) => console.error('profile crawl failed', String(e?.message || e).slice(0, 200)));
134
+ return { status: 'crawling', domain };
135
+ }));
136
+
137
+ server.registerTool('update_profile', {
138
+ description: 'Operator: edit the niche profile (niches [{name, keywords, enabled}], naics, negative_keywords, not_a_fit, summary) and re-screen open bids.',
139
+ inputSchema: {
140
+ niches: z.array(z.object({ name: z.string(), keywords: z.array(z.string()), enabled: z.boolean().optional() })).max(20).optional(),
141
+ naics: z.array(z.string()).max(20).optional(), negative_keywords: z.array(z.string()).max(120).optional(),
142
+ not_a_fit: z.array(z.string()).max(12).optional(), summary: z.string().max(1500).optional(),
143
+ },
144
+ }, op((edits) => {
145
+ const cur = getProfile();
146
+ const clean = Object.fromEntries(Object.entries(edits).filter(([, v]) => v !== undefined));
147
+ const p = saveProfile({ ...cur, ...clean, source: cur.source?.startsWith('site:') && !cur.source.endsWith('+edited') ? `${cur.source}+edited` : cur.source });
148
+ return { profile: p, screened: rescreen(p) };
149
+ }));
150
+
151
+ return server;
152
+ }
153
+
154
+ export async function handleMcp(request) {
155
+ const server = buildMcpServer({ isOperator: bearerIsOperator(request.headers.get('authorization')) });
156
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
157
+ await server.connect(transport);
158
+ return transport.handleRequest(request);
159
+ }
package/src/niche.js ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Niche matching: what the bidder actually does, as named niches with
3
+ * keywords, plus NAICS codes and things that are never a fit.
4
+ *
5
+ * A profile is derived from the bidder's own website (see profile.js: crawl,
6
+ * index, then a model names the niches) and can be edited by an operator. This
7
+ * module is pure: it compiles a profile into regexes and scores a solicitation
8
+ * against it. The active profile is set by profile.js; until a site has been
9
+ * read, DEFAULT_PROFILE (Profullstack's hand-written one) is used.
10
+ */
11
+
12
+ /** Niches a website is checked against when no model answers. Each keyword is a regex fragment, matched as whole words. */
13
+ export const NICHE_LIBRARY = [
14
+ { name: 'Custom software development', naics: ['541511'], keywords: ['software development', 'custom software', 'application development', 'app development', 'web application', 'web app', 'software engineering', 'full[ -]stack', 'saas', 'pwa', 'progressive web app', 'desktop app\\w*', 'software',
15
+ // How agencies title a software build.
16
+ 'case management (system|software|solution|platform)s?', 'system (implementation|replacement|modernization|development)', 'systems (implementation|replacement|modernization|development)', 'apis?'] },
17
+ { name: 'Software consulting', naics: ['541512', '541519', '541690'], keywords: ['software consult\\w*', 'it consult\\w*', 'technology consult\\w*', 'technical consult\\w*', 'it staff augmentation', 'staff augmentation', 'fractional cto', 'technical advisory', 'it services', 'information technology services', 'information technology', '(it|technology) modernization', 'systems integrator', 'solutions integrator'] },
18
+ { name: 'Agentic engineering', naics: ['541511', '541715'], keywords: ['agentic', 'ai agents?', 'autonomous agents?', 'llm', 'large language models?', 'generative ai', 'artificial intelligence', 'machine learning', 'chatbots?', 'model context protocol', 'conversational ai', 'natural language processing', 'ai'] },
19
+ { name: 'Business process automation', naics: ['541511', '541512'], keywords: ['automation', 'workflow automation', 'process automation', 'robotic process automation', 'rpa', 'workflow', 'document processing', 'integrations?', 'system integration', 'data pipelines?', 'etl'] },
20
+ { name: 'Cybersecurity', naics: ['541512', '541519'], keywords: ['cybersecurity', 'cyber security', 'information security', 'penetration test(ing)?', 'pentest\\w*', 'vulnerability (assessment|scanning|management)', 'security assessment', 'threat (monitoring|detection|intelligence)', 'siem', 'incident response', 'application security', 'web application firewall', 'security operations center'] },
21
+ { name: 'Web and mobile apps', naics: ['541511'], keywords: ['website', 'web portal', 'web design', 'web development', 'mobile apps?', 'mobile application', 'ios', 'android', 'content management system'] },
22
+ { name: 'Case management and CRM systems', naics: ['541512', '541511'], keywords: ['case management (system|software|solution|platform)s?', 'crm', 'customer relationship management', 'permit(ting)? (management|system|software)', 'licensing system', 'records management', 'erp', 'servicenow', 'salesforce'] },
23
+ { name: 'Cloud, hosting and DevOps', naics: ['518210', '541513'], keywords: ['cloud', 'hosting', 'devops', 'kubernetes', 'aws', 'azure', 'google cloud', 'infrastructure as code', 'site reliability', 'managed services', 'it support', 'it modernization', 'cloud migration'] },
24
+ { name: 'Data and analytics', naics: ['518210', '541512'], keywords: ['data analytics', 'data platform', 'data warehouse', 'business intelligence', 'dashboards?', 'data engineering', 'data science', 'reporting system'] },
25
+ { name: 'GPU and compute rental', naics: ['518210', '532420'], keywords: ['gpu', 'high performance computing', 'hpc', 'compute (capacity|rental|resources)', 'bare metal', 'server rental', 'ai inference'] },
26
+ { name: 'Blockchain and payments', naics: ['541511'], keywords: ['blockchain', 'cryptocurrenc\\w*', 'payment (gateway|processing|platform)', 'digital wallets?', 'web3'] },
27
+ ];
28
+
29
+ /** Words that sink a solicitation for a software/IT shop, whatever the website says. */
30
+ export const BASE_NEGATIVE = [
31
+ 'construction', 'janitorial', 'custodial', 'landscap\\w*', 'roofing', 'paving', 'hvac', 'plumbing', 'electrical contractor', 'food', 'catering',
32
+ 'vehicles?', 'tires', 'fuel', 'uniforms?', 'medical supplies', 'pharmacy', 'gift cards?', 'furniture', 'printing', 'asphalt', 'concrete',
33
+ 'valves?', 'gaskets?', 'ammunition', 'aircraft parts', 'nsn', 'repair parts', 'dredging', 'demolition', 'mowing', 'towing', 'airplane', 'aircraft maintenance',
34
+ 'transportation services', 'bus', 'housing', 'polygraph', 'psychiatric', 'psychological', 'sewing', 'water well', 'architectural', 'engineering services',
35
+ ];
36
+
37
+ /** Weak words: only count with a tech title, never alone. */
38
+ export const WEAK = ['computer', 'servers?', 'storage', 'network(ing)?', 'license', 'subscription', 'digital', 'database', 'technology', 'it'];
39
+
40
+ /** Profullstack's hand-written profile, used until the website has been read. */
41
+ export const DEFAULT_PROFILE = {
42
+ company: 'Profullstack, Inc.',
43
+ domain: 'profullstack.com',
44
+ summary:
45
+ 'Profullstack builds and operates custom software, web/mobile apps, APIs and AI agents; runs security work (vulnerability scanning, pentest support, threat monitoring via ThreatCrush); automates business processes (workflow and agentic automation, data pipelines, integrations); and rents compute (GPU and server capacity on the c0mpute network). Small business, California based, remote delivery.',
46
+ capabilities: [
47
+ 'Custom software development (web, mobile, PWA, desktop), API and integration work',
48
+ 'Case management, permitting, CRM and workflow systems: build, configure, integrate, migrate',
49
+ 'Cybersecurity: vulnerability assessment, application security review, monitoring, incident response support',
50
+ 'Automation: business process automation, AI agents, data pipelines, document processing',
51
+ 'Cloud and hosting operations, DevOps, software maintenance and support',
52
+ 'Hardware and compute rental: GPU and server capacity, on-demand',
53
+ ],
54
+ niches: NICHE_LIBRARY.filter((n) => !/blockchain/i.test(n.name)).map((n) => ({ ...n, enabled: true })),
55
+ negative_keywords: BASE_NEGATIVE,
56
+ naics: ['541511', '541512', '541513', '541519', '518210', '541690', '541715', '532420'],
57
+ not_a_fit: [
58
+ 'construction, facilities, janitorial, landscaping, food, vehicles, medical or clinical services',
59
+ 'physical goods resale that requires an authorized manufacturer reseller agreement the bidder does not hold',
60
+ 'staffing-only contracts requiring on-site cleared personnel',
61
+ ],
62
+ source: 'default',
63
+ };
64
+
65
+ const esc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
66
+
67
+ /**
68
+ * A keyword as typed by a person or a model -> a safe regex fragment. Library
69
+ * keywords are already fragments; anything else is escaped and lowercased.
70
+ */
71
+ export function keywordFragment(k, { trusted = false } = {}) {
72
+ const s = String(k || '').trim().toLowerCase().slice(0, 80);
73
+ if (!s) return null;
74
+ if (trusted) return s;
75
+ return esc(s).replace(/\s+/g, '\\s+');
76
+ }
77
+
78
+ const toRx = (frag) => {
79
+ try { return new RegExp(`(?<![\\w-])${frag}(?![\\w-])`, 'i'); } catch { return null; }
80
+ };
81
+
82
+ const LIB_KEYS = new Set(NICHE_LIBRARY.flatMap((n) => n.keywords));
83
+
84
+ /** One-word keywords that would match nearly every solicitation. Dropped unless they come from the library. */
85
+ export const GENERIC = new Set(['services', 'service', 'solutions', 'solution', 'support', 'management', 'consulting', 'consultant', 'development', 'design', 'systems', 'system',
86
+ 'technology', 'technologies', 'digital', 'data', 'platform', 'platforms', 'products', 'product', 'program', 'programs', 'operations', 'maintenance', 'training', 'engineering',
87
+ 'project', 'projects', 'professional', 'business', 'enterprise', 'modern', 'innovation', 'custom', 'web', 'online', 'it', 'tech', 'apps', 'tools', 'network', 'security']);
88
+ const usable = (k) => LIB_KEYS.has(k) || !GENERIC.has(k.toLowerCase());
89
+
90
+ /** Validate and tidy a profile from a model, a form or the DB. */
91
+ export function normalizeProfile(p = {}) {
92
+ const base = DEFAULT_PROFILE;
93
+ const list = (v, max = 60) => [...new Set((Array.isArray(v) ? v : String(v || '').split(/[,\n]/)).map((x) => String(x).trim()).filter(Boolean))].slice(0, max);
94
+ const niches = (Array.isArray(p.niches) ? p.niches : base.niches)
95
+ .map((n) => ({
96
+ name: String(n?.name || '').trim().slice(0, 80),
97
+ keywords: list(n?.keywords, 40).map((k) => k.slice(0, 80)).filter(usable),
98
+ enabled: n?.enabled !== false,
99
+ ...(n?.evidence ? { evidence: String(n.evidence).slice(0, 300) } : {}),
100
+ }))
101
+ .filter((n) => n.name && n.keywords.length)
102
+ .slice(0, 20);
103
+ return {
104
+ company: String(p.company || base.company).slice(0, 120),
105
+ domain: p.domain ? String(p.domain).slice(0, 253) : base.domain,
106
+ summary: String(p.summary || base.summary).slice(0, 1500),
107
+ capabilities: list(p.capabilities ?? base.capabilities, 20),
108
+ niches: niches.length ? niches : base.niches,
109
+ negative_keywords: list(p.negative_keywords ?? base.negative_keywords, 120),
110
+ naics: list(p.naics ?? base.naics, 20).filter((c) => /^\d{2,6}$/.test(c)),
111
+ not_a_fit: list(p.not_a_fit ?? base.not_a_fit, 12),
112
+ source: p.source || 'custom',
113
+ ...(p.crawled_at ? { crawled_at: p.crawled_at } : {}),
114
+ ...(p.pages ? { pages: p.pages } : {}),
115
+ ...(p.method ? { method: p.method } : {}),
116
+ ...(p.ai_error ? { ai_error: String(p.ai_error).slice(0, 300) } : {}),
117
+ };
118
+ }
119
+
120
+ /** Profile -> compiled matchers. Cached per profile object. */
121
+ const compiled = new WeakMap();
122
+ export function compile(profile) {
123
+ let c = compiled.get(profile);
124
+ if (c) return c;
125
+ const frag = (k) => keywordFragment(k, { trusted: LIB_KEYS.has(k) });
126
+ const niches = profile.niches
127
+ .filter((n) => n.enabled !== false)
128
+ .map((n) => ({ name: n.name, rx: n.keywords.map((k) => ({ k, r: toRx(frag(k)) })).filter((x) => x.r) }));
129
+ c = {
130
+ niches,
131
+ weak: WEAK.map((w) => toRx(w)),
132
+ negative: profile.negative_keywords.map((k) => ({ k, r: toRx(keywordFragment(k, { trusted: BASE_NEGATIVE.includes(k) })) })).filter((x) => x.r),
133
+ naics: profile.naics,
134
+ };
135
+ compiled.set(profile, c);
136
+ return c;
137
+ }
138
+
139
+ /** Label for a solicitation that matches only on one of our NAICS codes. */
140
+ export const NAICS_NICHE = 'Our NAICS codes';
141
+
142
+ let active = normalizeProfile({ ...DEFAULT_PROFILE, source: 'default' });
143
+ export const activeProfile = () => active;
144
+ export function setActiveProfile(p) {
145
+ active = p ? normalizeProfile(p) : normalizeProfile({ ...DEFAULT_PROFILE, source: 'default' });
146
+ return active;
147
+ }
148
+
149
+ /**
150
+ * Which of our niches a solicitation falls in. The title leads: a long notice
151
+ * carries boilerplate ("cloud", "workflow"), so body hits count only when the
152
+ * title is about technology too, or the NAICS code is ours.
153
+ * Returns { score 0-30, niches: [names], keywords: [hits], naics: bool, negative: [hits] }.
154
+ */
155
+ export function nicheMatch({ title = '', description = '', naics = '' } = {}, profile = active) {
156
+ const c = compile(profile);
157
+ const head = String(title);
158
+ const body = String(description).slice(0, 1500);
159
+ const n = String(naics || '');
160
+ const naicsHit = c.naics.some((code) => n.includes(code)) ? 4 : /^54151|^5182/.test(n) ? 3 : 0;
161
+ const weakTitle = c.weak.filter((r) => r.test(head)).length;
162
+ const hits = [];
163
+ const titleNiches = new Set();
164
+ const bodyNiches = new Set();
165
+ let strongTitle = 0;
166
+ let strongBody = 0;
167
+ const seen = new Set();
168
+ for (const nn of c.niches) {
169
+ for (const { k, r } of nn.rx) {
170
+ if (r.test(head)) { titleNiches.add(nn.name); if (!seen.has(k)) { seen.add(k); strongTitle++; hits.push(k); } }
171
+ else if (r.test(body)) { bodyNiches.add(nn.name); if (!seen.has(k)) { seen.add(k); strongBody++; hits.push(k); } }
172
+ }
173
+ }
174
+ const negative = c.negative.filter(({ r }) => r.test(head)).map(({ k }) => k);
175
+ const bodyCounts = strongTitle > 0 || naicsHit > 0 || weakTitle > 0;
176
+ const passes = strongTitle || naicsHit || (strongBody && weakTitle);
177
+ if (!passes) return { score: 0, niches: [], keywords: [], naics: false, negative };
178
+ let score = strongTitle * 4 + (bodyCounts ? strongBody * 2 : 0) + weakTitle + naicsHit;
179
+ score -= negative.length * 5;
180
+ score = Math.max(0, Math.min(score, 30));
181
+ const niches = score > 0 ? [...titleNiches, ...(bodyCounts ? [...bodyNiches].filter((x) => !titleNiches.has(x)) : [])] : [];
182
+ if (score > 0 && !niches.length && naicsHit) niches.push(NAICS_NICHE);
183
+ return { score, niches, keywords: score > 0 ? hits.slice(0, 12) : [], naics: naicsHit > 0, negative };
184
+ }
185
+
186
+ /** The fit model's system prompt describes the bidder from the profile. */
187
+ export function profileBrief(p = active) {
188
+ const niches = p.niches.filter((n) => n.enabled !== false).map((n) => n.name);
189
+ return `Company: ${p.company}${p.domain ? ` (${p.domain})` : ''}
190
+ ${p.summary}
191
+ Niches we bid in: ${niches.join('; ')}.
192
+ Capabilities:
193
+ - ${p.capabilities.join('\n- ')}
194
+ NAICS: ${p.naics.join(', ')}
195
+ Not a fit: ${p.not_a_fit.join('; ')}.`;
196
+ }