@profullstack/gov-contracts 0.1.0 → 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/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
+ }
package/src/pages.js CHANGED
@@ -83,6 +83,9 @@ input[type=text],input[type=search],select{background:var(--card);color:var(--fg
83
83
  .err{color:var(--bad)}.ok{color:var(--ok)}
84
84
  pre{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;white-space:pre-wrap}
85
85
  .foot{max-width:1100px;margin:40px auto 0;padding:0 16px;color:var(--mute)}
86
+ .chips{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0}.chips a{text-decoration:none}.pill.niche{color:var(--acc2);border-color:var(--acc2)}
87
+ .niche-row{display:grid;grid-template-columns:auto 1fr;gap:6px 12px;align-items:start;border-top:1px solid var(--line);padding:10px 0}
88
+ textarea.kw{width:100%;min-height:60px;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:9px;padding:8px}
86
89
  `;
87
90
 
88
91
  async function layout({ title, description, path = '/', signedIn = null }, body) {
@@ -105,7 +108,7 @@ async function layout({ title, description, path = '/', signedIn = null }, body)
105
108
  <script type="module" data-webmcp src="https://cdn.jsdelivr.net/npm/@profullstack/webmcp@0.2.1/src/embed.js" data-mcp="/mcp" data-pages='{"home":"/","solicitations":"/solicitations","docs":"/docs"}'></script>
106
109
  </head>
107
110
  <body>
108
- <header class="top"><a class="brand" href="/">gov<span>.procurement</span></a><nav><a href="/solicitations">Solicitations</a><a href="/docs">Docs</a>${auth}</nav></header>
111
+ <header class="top"><a class="brand" href="/">gov<span>.procurement</span></a><nav><a href="/solicitations">Solicitations</a><a href="/profile">Niches</a><a href="/docs">Docs</a>${auth}</nav></header>
109
112
  <main>${body}</main>
110
113
  ${site}
111
114
  ${pit}
@@ -132,13 +135,14 @@ export function mdLite(text) {
132
135
  return out.join('');
133
136
  }
134
137
 
138
+ const nichePills = (s) => (Array.isArray(s.niches) && s.niches.length ? `<div>${s.niches.slice(0, 3).map((n) => `<span class="pill niche">${h(n)}</span>`).join('')}</div>` : '');
135
139
  const fitPill = (s) => (s.fit_score != null ? `<span class="pill fit" title="fit score">${h(s.fit_score)}</span>` : '');
136
140
  const due = (d) => (d ? h(String(d).slice(0, 10)) : '');
137
141
 
138
142
  function solTable(rows, { showFit }) {
139
143
  if (!rows.length) return '<p class="note">Nothing here yet. The first ingest runs a minute after start; sources refresh every 6 hours.</p>';
140
144
  return `<div class="tw"><table><thead><tr>${showFit ? '<th>Fit</th>' : ''}<th>Solicitation</th><th>Buyer</th><th>Due</th><th>Source</th></tr></thead><tbody>${rows
141
- .map((s) => `<tr>${showFit ? `<td>${fitPill(s) || `<span class="pill">${h(s.status)}</span>`}</td>` : ''}<td><a href="/s/${encodeURIComponent(s.id)}">${h(s.title)}</a>${s.number ? `<div class="note">${h(s.number)}</div>` : ''}</td><td>${h(s.agency || '')}<div class="note">${h(s.level || '')}${s.region ? ' · ' + h(s.region) : ''}</div></td><td>${due(s.due_at)}</td><td>${h(s.source)}</td></tr>`)
145
+ .map((s) => `<tr>${showFit ? `<td>${fitPill(s) || `<span class="pill">${h(s.status)}</span>`}</td>` : ''}<td><a href="/s/${encodeURIComponent(s.id)}">${h(s.title)}</a>${s.number ? `<div class="note">${h(s.number)}</div>` : ''}${nichePills(s)}</td><td>${h(s.agency || '')}<div class="note">${h(s.level || '')}${s.region ? ' · ' + h(s.region) : ''}</div></td><td>${due(s.due_at)}</td><td>${h(s.source)}</td></tr>`)
142
146
  .join('')}</tbody></table></div>`;
143
147
  }
144
148
 
@@ -149,12 +153,14 @@ ${error ? `<p class="warn err">${h(error)}</p>` : ''}
149
153
  <p class="lede">gov.procurement watches federal, state, county and city bid sources, reads each RFP, scores how well it fits what we do (software, security, automation, hardware rental), drafts a compliant proposal and puts every step that needs a human into one queue: price it, sign the forms, register on the portal, review and submit.</p>
150
154
  <div class="stats">
151
155
  <div class="stat"><b>${h(stats.open_solicitations)}</b><span>open solicitations</span></div>
156
+ <div class="stat"><b>${h(stats.in_niche ?? 0)}</b><span>in our niches</span></div>
152
157
  <div class="stat"><b>${h(stats.by_status?.scored || 0)}</b><span>scored, not drafted</span></div>
153
158
  <div class="stat"><b>${h(stats.drafts)}</b><span>proposal drafts</span></div>
154
159
  <div class="stat"><b>${h(stats.interventions_open)}</b><span>waiting on a person</span></div>
155
160
  </div>
156
161
  <p class="warn"><b>Never automatic:</b> ${Object.values(HUMAN_ONLY).join('; ')}. Those are queue cards only.</p>
157
- <h2>${isOperator ? 'Best fits' : 'Recently found'}</h2>
162
+ <h2>${isOperator ? 'Best fits in our niches' : 'Recently found in our niches'}</h2>
163
+ <p class="note">Niches are read from our own website. <a href="/profile">See or change them</a>.</p>
158
164
  ${solTable(top, { showFit: isOperator })}
159
165
  <p><a class="btn" href="/solicitations">All open solicitations</a> ${signedIn ? '<a class="btn primary" href="/queue">Open the queue</a>' : '<a class="btn primary" href="/signin?next=/queue">Sign in with CoinPay</a>'}</p>
160
166
  <h2>Every surface</h2>
@@ -162,10 +168,12 @@ ${solTable(top, { showFit: isOperator })}
162
168
  return layout({ title: 'gov.procurement: government contract opportunities, read and drafted', description: 'Find federal, state and local government contract opportunities, read the RFP, score the fit and draft a proposal. Every submission stays a human step.', signedIn }, body);
163
169
  }
164
170
 
165
- export async function solicitationsPage({ rows, q, level, source, signedIn, isOperator }) {
171
+ export async function solicitationsPage({ rows, q, level, source, niche = 'in', niches = [], profile, signedIn, isOperator }) {
166
172
  const opt = (v, cur, label) => `<option value="${h(v)}"${v === cur ? ' selected' : ''}>${h(label)}</option>`;
167
173
  const body = `<h1>Open solicitations</h1>
174
+ <p class="note">${niche === 'all' ? 'Every open bid.' : niche === 'in' ? `Only bids in our niches, read from <a href="/profile">${h(profile?.domain || 'our site')}</a>.` : niche === 'out' ? 'Bids outside our niches.' : `Niche: ${h(niche)}.`}</p>
168
175
  <form class="row" method="get" action="/solicitations">
176
+ <select name="niche" aria-label="Niche">${opt('in', niche, 'Our niches')}${niches.map((n) => opt(n.niche, niche, `${n.niche} (${n.n})`)).join('')}${opt('out', niche, 'Outside our niches')}${opt('all', niche, 'Everything')}</select>
169
177
  <input type="search" name="q" value="${h(q || '')}" placeholder="software, permit, cybersecurity..." aria-label="Search">
170
178
  <select name="level" aria-label="Level">${opt('', level || '', 'Any level')}${['federal', 'state', 'county', 'city'].map((l) => opt(l, level, l)).join('')}</select>
171
179
  <select name="source" aria-label="Source">${opt('', source || '', 'Any source')}${['sam', 'lacounty', 'digest'].map((l) => opt(l, source, l)).join('')}</select>
@@ -214,6 +222,7 @@ export function cardHtml(iv) {
214
222
  return `<article class="card" id="iv-${h(iv.id)}">
215
223
  <div class="eyebrow">${h(KIND_LABEL[iv.kind] || iv.kind)}${iv.due_at ? ` · due ${due(iv.due_at)}` : ''}${iv.fit_score != null ? ` · fit ${h(iv.fit_score)}` : ''}${resolved ? ` · ${h(iv.status)}` : ''}</div>
216
224
  <h3>${h(iv.title)}</h3>
225
+ ${Array.isArray(iv.niches) && iv.niches.length ? `<div>${iv.niches.slice(0, 3).map((n) => `<span class="pill niche">${h(n)}</span>`).join('')}</div>` : ''}
217
226
  ${iv.agency ? `<div class="meta">${h(iv.agency)}${iv.number ? ` · ${h(iv.number)}` : ''}${iv.solicitation_id ? ` · <a href="/s/${encodeURIComponent(iv.solicitation_id)}">solicitation</a>` : ''}${iv.proposal_id ? ` · <a href="/p/${h(iv.proposal_id)}">proposal</a>` : ''}</div>` : ''}
218
227
  ${mdLite(iv.body)}
219
228
  ${iv.copy_text ? `<textarea readonly id="copy-${h(iv.id)}" aria-label="Text to copy">${h(iv.copy_text)}</textarea><div class="note">${h(iv.copy_text.length)} characters</div>` : ''}
@@ -231,10 +240,14 @@ ${resolved ? `<p class="note">${h(iv.status)} ${iv.resolved_at ? h(iv.resolved_a
231
240
 
232
241
  const COPY_JS = `<script>document.addEventListener('click',e=>{const b=e.target.closest('[data-copy]');if(!b)return;const t=document.getElementById(b.dataset.copy);navigator.clipboard.writeText(t.value).then(()=>{b.textContent='Copied';setTimeout(()=>b.textContent='Copy',1500)})});</script>`;
233
242
 
234
- export async function queuePage({ items, status, counts, account }) {
235
- const tab = (v, label) => `<a class="btn${status === v ? ' primary' : ''}" href="/queue?status=${v}">${label}${counts[v] != null ? ` (${counts[v]})` : ''}</a>`;
243
+ export async function queuePage({ items, status, counts, niche = 'in', hidden = 0, niches = [], profile, account }) {
244
+ const qs = (o) => new URLSearchParams({ status, niche, ...o }).toString();
245
+ const tab = (v, label) => `<a class="btn${status === v ? ' primary' : ''}" href="/queue?${qs({ status: v })}">${label}${counts[v] != null ? ` (${counts[v]})` : ''}</a>`;
246
+ const chip = (v, label) => `<a class="pill${niche === v ? ' fit' : ''}" href="/queue?${qs({ niche: v })}">${h(label)}</a>`;
236
247
  const body = `<h1>Interventions</h1>
237
248
  <p class="lede">Everything the system cannot do on its own. Signed in as ${h(account?.name || 'operator')}.</p>
249
+ <div class="chips">${chip('in', 'Our niches')}${niches.slice(0, 10).map((n) => chip(n.niche, n.niche)).join('')}${chip('all', 'Everything')}</div>
250
+ ${hidden > 0 ? `<p class="note">${h(hidden)} card${hidden === 1 ? '' : 's'} outside ${niche === 'in' ? 'our niches' : h(niche)} hidden. <a href="/queue?${qs({ niche: 'all' })}">Show everything</a> or <a href="/profile">change the niches</a> (read from ${h(profile?.domain || 'our site')}).</p>` : ''}
238
251
  <div class="row">${tab('open', 'Open')}${tab('done', 'Done')}${tab('dismissed', 'Dismissed')}${tab('all', 'All')}</div>
239
252
  <div class="cards">${items.length ? items.map(cardHtml).join('') : '<p class="note">Nothing waiting on you.</p>'}</div>${COPY_JS}`;
240
253
  return layout({ title: 'Queue · gov.procurement', description: 'Human intervention queue.', path: '/queue', signedIn: account }, body);
@@ -249,6 +262,35 @@ export async function proposalPage({ p, s, account }) {
249
262
  return layout({ title: `Proposal: ${s.title}`, description: 'Proposal draft', path: `/p/${p.id}`, signedIn: account }, body);
250
263
  }
251
264
 
265
+ export async function profilePage({ p, pages, running, library, isOperator, signedIn, notice }) {
266
+ const vias = pages.reduce((a, x) => ({ ...a, [x.via]: (a[x.via] || 0) + 1 }), {});
267
+ const niches = p.niches.map((n, i) => (isOperator
268
+ ? `<div class="niche-row"><input type="checkbox" name="enabled" value="${i}" id="n${i}"${n.enabled !== false ? ' checked' : ''}><div><label for="n${i}"><b>${h(n.name)}</b></label>${n.evidence ? `<div class="note">${h(n.evidence)}</div>` : ''}<textarea class="kw" name="kw_${i}" aria-label="Keywords for ${h(n.name)}">${h(n.keywords.join(', '))}</textarea></div></div>`
269
+ : `<div class="niche-row"><span class="pill${n.enabled !== false ? ' fit' : ''}">${n.enabled !== false ? 'on' : 'off'}</span><div><b>${h(n.name)}</b>${n.evidence ? `<div class="note">${h(n.evidence)}</div>` : ''}<div class="note">${h(n.keywords.slice(0, 14).join(', '))}</div></div></div>`)).join('');
270
+ const missing = library.filter((l) => !p.niches.some((n) => n.name.toLowerCase() === l.name.toLowerCase()));
271
+ const source = p.source === 'default' ? 'hand-written default (site not read yet)' : p.source;
272
+ const body = `<h1>Our niches</h1>
273
+ ${notice ? `<p class="warn">${h(notice)}</p>` : ''}
274
+ ${running ? `<p class="warn">Reading ${h(running)} now. Refresh in a minute.</p>` : ''}
275
+ <p class="lede">${h(p.summary)}</p>
276
+ <p><span class="pill">${h(p.company)}</span>${p.domain ? `<span class="pill">${h(p.domain)}</span>` : ''}<span class="pill">${h(source)}</span>${p.method ? `<span class="pill">${h(p.method)}</span>` : ''}${p.crawled_at ? `<span class="pill">read ${h(String(p.crawled_at).slice(0, 16).replace('T', ' '))}</span>` : ''}<span class="pill">${h(p.indexed_pages ?? pages.length)} pages indexed</span>${Object.entries(vias).map(([k, v]) => `<span class="pill">${h(k)}: ${h(v)}</span>`).join('')}</p>
277
+ ${p.ai_error ? `<p class="note err">The model did not answer (${h(p.ai_error)}); niches come from the site's own wording.</p>` : ''}
278
+ <p class="note">Every bid is matched against these niches (title first; NAICS ${h(p.naics.join(', '))} counts too). Bids outside them are never read, scored or drafted, and their cards stay out of the queue's default view.</p>
279
+ ${isOperator ? `<form method="post" action="/profile" class="row"><input type="hidden" name="action" value="crawl"><input type="text" name="domain" value="${h(p.domain || '')}" aria-label="Domain" placeholder="profullstack.com"><input type="text" name="max_pages" value="40" aria-label="Pages" size="4"><button class="primary"${running ? ' disabled' : ''}>Read the site again</button></form>
280
+ <p class="note">Pages are fetched through c0mpute (crawl.fetch) when a worker is free, otherwise directly (robots.txt honoured). A model (c0mpute first) names the niches; niches you switch off stay off after a re-read.</p>
281
+ <form method="post" action="/profile">
282
+ <h2>Niches</h2>${niches}
283
+ <h2>Add a niche</h2>
284
+ <div class="row"><input type="text" name="new_name" list="lib" placeholder="Agentic engineering" aria-label="Niche name" style="flex:1"><datalist id="lib">${missing.map((l) => `<option value="${h(l.name)}">`).join('')}</datalist></div>
285
+ <textarea class="kw" name="new_keywords" placeholder="keywords a bid title would use, comma separated (blank = the library's list for that name)" aria-label="New niche keywords"></textarea>
286
+ <h2>NAICS codes</h2><input type="text" name="naics" value="${h(p.naics.join(', '))}" style="width:100%" aria-label="NAICS codes">
287
+ <h2>Never a fit</h2><textarea class="kw" name="negative" aria-label="Negative keywords">${h(p.negative_keywords.join(', '))}</textarea>
288
+ <p class="row"><button class="primary">Save and re-screen open bids</button></p></form>`
289
+ : `<h2>Niches</h2>${niches}<p class="note">Operators can edit these after signing in.</p>`}
290
+ ${pages.length ? `<h2>Pages read</h2><ul>${pages.slice(0, 60).map((x) => `<li><a href="${h(x.url)}" rel="noopener" target="_blank">${h(x.title || x.url)}</a> <span class="note">${h(x.via)} · ${h(x.text_chars || 0)} chars</span></li>`).join('')}</ul>` : ''}`;
291
+ return layout({ title: 'Our niches · gov.procurement', description: 'The niches bids are filtered by, read from our own website.', path: '/profile', signedIn }, body);
292
+ }
293
+
252
294
  export async function messagePage({ title, message, signedIn, status = 200 }) {
253
295
  return { status, html: await layout({ title: `${title} · gov.procurement`, description: title, signedIn }, `<h1>${h(title)}</h1><p class="lede">${message}</p>`) };
254
296
  }
@@ -263,6 +305,10 @@ export const MCP_TOOLS_DOC = [
263
305
  ['resolve_intervention', 'Operator: mark a card done or dismissed (records what a PERSON did).'],
264
306
  ['draft_proposal', 'Operator: queue a (re)draft for a solicitation.'],
265
307
  ['ingest_digest', 'Operator: add the solicitations listed in a forwarded bid digest.'],
308
+ ['get_profile', 'Our niche profile (read from our website) and open bids per niche.'],
309
+ ['search_profile_pages', 'Full-text search over our indexed website pages.'],
310
+ ['crawl_profile', 'Operator: re-read a website and re-derive the niches.'],
311
+ ['update_profile', 'Operator: edit niches, NAICS and never-a-fit words; re-screens open bids.'],
266
312
  ];
267
313
 
268
314
  export async function docsPage({ signedIn }) {
@@ -271,11 +317,14 @@ export async function docsPage({ signedIn }) {
271
317
  <h2 id="pipeline">Pipeline</h2>
272
318
  <ol><li><b>Ingest</b> every 6 h: SAM.gov opportunities (federal), County of Los Angeles open solicitations; forwarded bid digests on demand. Where to look comes from Datamart's contracts registry (<code>contracts_sources</code>).</li>
273
319
  <li><b>Read</b>: the full notice, NAICS, set-aside, contacts, and the text of up to 3 public PDF attachments.</li>
320
+ <li><b>Niche</b>: our niches are read from our own website (<a href="/profile">/profile</a>): the spider fetches its pages through c0mpute <code>crawl.fetch</code> (direct when no worker is free), indexes them, and a model names the niches and the words a bid title uses for each. Every bid is matched against them; bids outside them stop here.</li>
274
321
  <li><b>Fit</b>: a keyword pre-filter, then a model (c0mpute first, OpenAI/Claude fallback) scores 0-100 against our capabilities and lists requirements, forms and registrations.</li>
275
322
  <li><b>Draft</b> (fit 60+): cover letter, technical approach, compliance matrix, forms checklist, pricing structure with every number blank.</li>
276
323
  <li><b>Queue</b>: register on the portal, set the price, sign/certify forms, review and submit by hand. 40-59 asks a person "worth a bid?".</li></ol>
277
324
  <h2 id="api">HTTP API</h2>
278
- <pre>GET /api/v1/solicitations?q=&level=&source=&limit=&order=fit|due|new
325
+ <pre>GET /api/v1/solicitations?q=&level=&source=&niche=in|out|all|&lt;niche name&gt;&limit=&order=fit|due|new|niche
326
+ GET /api/v1/profile our niches, read from our website
327
+ GET /api/v1/profile/search?q= full-text search over the indexed site
279
328
  GET /api/v1/solicitations/:id
280
329
  GET /api/v1/sources
281
330
  GET /api/v1/stats
@@ -285,13 +334,19 @@ POST /api/v1/interventions/:id {"status":"done"|"dismissed"|"open","note"
285
334
  GET /api/v1/proposals/:id (?format=md)
286
335
  POST /api/v1/solicitations/:id/draft
287
336
  POST /api/v1/ingest/digest {"text":"...forwarded digest body..."}
288
- POST /api/v1/run/:job ingest-sam | ingest-lacounty | work</pre>
337
+ POST /api/v1/run/:job ingest-sam | ingest-lacounty | work | profile | rescreen
338
+ POST /api/v1/profile/crawl {"domain":"profullstack.com","max_pages":40}
339
+ POST /api/v1/profile/pages {"domain":"...","pages":[{"url","title","text","via"}]} (pages you read yourself)
340
+ PUT /api/v1/profile {"niches":[{"name","keywords","enabled"}],"naics":[],"negative_keywords":[]}</pre>
289
341
  <h2 id="mcp">MCP</h2>
290
342
  <p>Streamable HTTP at <code>${h(SITE)}mcp</code>. Operator tools need the Bearer key on the connection.</p>
291
343
  <table><tbody>${MCP_TOOLS_DOC.map(([n, d]) => `<tr><td><code>${n}</code></td><td>${h(d)}</td></tr>`).join('')}</tbody></table>
292
344
  <h2 id="cli">CLI and TUI</h2>
293
345
  <pre>npx @profullstack/gov-contracts search software --level county
294
346
  gov-contracts show sam:&lt;id&gt;
347
+ gov-contracts niches # our niche profile
348
+ gov-contracts search software --niche "Agentic engineering"
349
+ gov-contracts profile crawl profullstack.com --local # read the site here with the c0mpute spider, then upload
295
350
  gov-contracts queue # needs GOV_CONTRACTS_KEY
296
351
  gov-contracts done &lt;card-id&gt; "confirmation 12345"
297
352
  gov-contracts digest &lt; digest.txt
package/src/pipeline.js CHANGED
@@ -9,6 +9,7 @@ import { ADAPTERS, adapterFor } from './sources/index.js';
9
9
  import { parseDigest } from './sources/digest.js';
10
10
  import { draftProposal, queueDecision } from './propose.js';
11
11
  import { scoreFit } from './fit.js';
12
+ import { buildProfile, loadProfile, rescreen } from './profile.js';
12
13
  import { USER_AGENT } from './http.js';
13
14
  import {
14
15
  documentsFor, dueFor, findFeedTwin, getSolicitation, logRun, openDb, saveDocument, setSolicitation, upsertSolicitation,
@@ -59,6 +60,11 @@ export async function readOne(sol) {
59
60
 
60
61
  /** Score one solicitation; drafts or asks a person depending on the score. */
61
62
  export async function scoreOne(sol, { ai = makeAi() } = {}) {
63
+ // Out of our niche (the profile changed since it was read): no model call, no card.
64
+ if (!(sol.niche_score > 0) && sol.niche_score != null) {
65
+ setSolicitation(sol.id, { status: 'skipped' });
66
+ return null;
67
+ }
62
68
  const docs = documentsFor(sol.id);
63
69
  const fit = await scoreFit(sol, docs, { ai });
64
70
  setSolicitation(sol.id, { fit, fit_score: fit.score, status: 'scored' });
@@ -74,7 +80,7 @@ export async function draftOne(sol, { ai = makeAi() } = {}) {
74
80
 
75
81
  /** Solicitations scored high enough by a model, not drafted yet. */
76
82
  function readyToDraft(limit) {
77
- return openDb().prepare(`SELECT id FROM solicitations WHERE status = 'scored' AND fit_score >= ? AND json_extract(fit, '$.method') = 'ai'
83
+ return openDb().prepare(`SELECT id FROM solicitations WHERE status = 'scored' AND fit_score >= ? AND json_extract(fit, '$.method') = 'ai' AND niche_score > 0
78
84
  AND (due_at IS NULL OR due_at >= ?) ORDER BY fit_score DESC, due_at ASC LIMIT ?`).all(DRAFT_MIN(), new Date().toISOString().slice(0, 10), limit).map((r) => getSolicitation(r.id));
79
85
  }
80
86
 
@@ -95,11 +101,27 @@ export async function workTick({ read = 3, score = 1, draft = 1 } = {}) {
95
101
  return done;
96
102
  }
97
103
 
104
+ /** Load the saved niche profile; give solicitations saved before 0.2.0 their niche match. */
105
+ export function bootProfile() {
106
+ const p = loadProfile();
107
+ const missing = openDb().prepare('SELECT COUNT(*) AS n FROM solicitations WHERE niche_score IS NULL').get().n;
108
+ if (missing) rescreen(p);
109
+ return p;
110
+ }
111
+
112
+ /** Re-read the bidder's website when the profile is older than PROFILE_EVERY (or was never read). */
113
+ export async function profileTick() {
114
+ const domain = process.env.PROFILE_DOMAIN || 'profullstack.com';
115
+ if (process.env.PROFILE_DISABLED === '1' || !domain) return { skipped: 'disabled' };
116
+ return buildProfile(domain, { maxPages: Number(process.env.PROFILE_MAX_PAGES || 40) });
117
+ }
118
+
98
119
  let daemon = null;
99
120
 
100
121
  /** Start the scheduled updater (ingest every 6 h per source, work loop every minute). */
101
122
  export function startDaemon() {
102
123
  if (daemon || process.env.DAEMON_DISABLED === '1') return daemon;
124
+ bootProfile();
103
125
  daemon = createDaemon({
104
126
  name: 'gov-contracts',
105
127
  store: sqliteStore(openDb(), { prefix: 'daemon' }),
@@ -111,6 +133,7 @@ export function startDaemon() {
111
133
  daemon.job({ name: `ingest-${name}`, every: a.every, staleAfter: '1d', run: () => ingestSource(name) });
112
134
  }
113
135
  daemon.job({ name: 'work', every: process.env.WORK_EVERY || '1m', staleAfter: '2h', run: () => workTick() });
136
+ daemon.job({ name: 'profile', every: process.env.PROFILE_EVERY || '7d', staleAfter: '14d', run: () => profileTick() });
114
137
  daemon.start();
115
138
  return daemon;
116
139
  }