@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/README.md CHANGED
@@ -3,10 +3,12 @@
3
3
  Find government contract opportunities, read the RFP, score the fit, draft the proposal, and queue every step that needs a person. Hosted at **gov.procurement** (Moshpit name; clearnet relay `https://gov.procurement.pit.world`).
4
4
 
5
5
  ```
6
- ingest -> read the RFP -> score the fit -> draft a proposal -> human queue
7
- (6 h) notice + PDFs c0mpute AI letter, approach, price it, sign forms,
8
- (OpenAI/Claude compliance, forms, register on the portal,
9
- fallback) pricing structure review and SUBMIT BY HAND
6
+ our website -> spider (c0mpute crawl.fetch) -> index (FTS5) -> AI names our niches (weekly, /profile)
7
+ |
8
+ ingest -> niche filter -> read the RFP -> score the fit -> draft a proposal -> human queue
9
+ (6 h) out-of-niche notice + PDFs c0mpute AI letter, approach, price it, sign forms,
10
+ bids stop here (OpenAI/Claude compliance, forms, register on the portal,
11
+ fallback) pricing structure review and SUBMIT BY HAND
10
12
  ```
11
13
 
12
14
  ## The hard line
@@ -25,16 +27,27 @@ Where to look comes from Datamart's contracts registry (the Profullstack connect
25
27
 
26
28
  Cal eProcure and most city portals block automated reads; their bids arrive through digests, and the queue tells a person where to look.
27
29
 
30
+ ## Our niches, read from our website
31
+
32
+ Bids are filtered by what the bidder actually sells, read from its own site (`PROFILE_DOMAIN`, default `profullstack.com`), not a hand-written list:
33
+
34
+ 1. **Spider** (`src/spider.js`): sitemap first, then same-site links, service and about pages first, up to `PROFILE_MAX_PAGES` (40). Each page is fetched through c0mpute's `crawl.fetch` workload first, via a `c0mpute jobs serve` bridge (`C0MPUTE_JOBS_URL` + `C0MPUTE_JOBS_TOKEN`) or the local `c0mpute crawl fetch` CLI (`C0MPUTE_CRAWL_CLI=1`). When the network has no free crawl worker (`network_busy`, twice) or neither is set, pages are read directly (robots.txt, public addresses only, one request at a time). Every page records which path read it.
35
+ 2. **Index** (`src/profile.js`): pages go into SQLite with an FTS5 index (`/api/v1/profile/search`, MCP `search_profile_pages`), so a proposal can cite what the site says.
36
+ 3. **Niches**: a model (c0mpute first, OpenAI/Claude fallback) names 3-8 niches, the words a bid title uses for each, NAICS codes and what is never a fit. A niche whose keywords never appear on the site is dropped; generic one-word keywords ("services", "solutions") are dropped; library niches the site clearly uses (`NICHE_LIBRARY` in `src/niche.js`: software development, software consulting, agentic engineering, automation, cybersecurity, cloud, GPU rental...) are added by name. With no model the library alone decides.
37
+ 4. **Filter**: every bid gets a niche match (title first; body words count only with a tech title or one of our NAICS codes; never-a-fit words sink it). Out-of-niche bids are never read, scored or drafted. `/solicitations` and the queue show **Our niches** by default, with one chip per niche and "Everything". A new or edited profile re-screens every open bid.
38
+
39
+ Operators edit it at `/profile` (switch niches off, change keywords, add a niche, NAICS, never-a-fit words); switched-off niches stay off after the weekly re-read. CLI: `gov-contracts niches`, `gov-contracts profile crawl profullstack.com --local` (crawl from your machine with the c0mpute spider, then upload), `gov-contracts profile set --off "Blockchain and payments"`.
40
+
28
41
  ## Fit and drafts
29
42
 
30
- A free keyword pre-filter (whole words, title-led, our NAICS codes) keeps the model to the bids that could matter. The model (c0mpute first via `@profullstack/ai-providers`, Anthropic/OpenAI fallback, short c0mpute timeout) returns a 0-100 score, verdict, requirements, forms and registrations. Brand-name license/renewal/maintenance buys are capped at 45 (they need an authorized reseller). 60+ gets a draft in three small parts; 40-59 gets a "worth a bid?" card. Drafts never contain a price, and only list forms whose names appear in what was read.
43
+ The niche filter keeps the model to the bids that could matter. The model (c0mpute first via `@profullstack/ai-providers`, Anthropic/OpenAI fallback, short c0mpute timeout) returns a 0-100 score, verdict, requirements, forms and registrations. Brand-name license/renewal/maintenance buys are capped at 45 (they need an authorized reseller). 60+ gets a draft in three small parts; 40-59 gets a "worth a bid?" card. Drafts never contain a price, and only list forms whose names appear in what was read.
31
44
 
32
45
  ## Surfaces
33
46
 
34
- - **Web / PWA**: `/` (stats, best fits), `/solicitations`, `/s/:id`, `/queue` (Sign in with CoinPay; operators by CoinPay `sub` allowlist, never email), `/p/:id` proposal. Installable.
35
- - **HTTP API**: `/api/v1/solicitations`, `/sources`, `/stats`; operator: `/interventions`, `/proposals/:id`, `/solicitations/:id/draft`, `/ingest/digest`, `/run/:job`. See `/docs`.
36
- - **MCP**: streamable HTTP at `/mcp`: `search_solicitations`, `get_solicitation`, `list_sources`, `stats`; operator (Bearer key): `list_interventions`, `get_proposal`, `resolve_intervention`, `draft_proposal`, `ingest_digest`.
37
- - **CLI + TUI**: `npx @profullstack/gov-contracts search software`, `queue`, `card`, `done`, `tui`, `mcp` (stdio bridge), `serve`.
47
+ - **Web / PWA**: `/` (stats, best fits in our niches), `/solicitations?niche=`, `/profile` (our niches), `/s/:id`, `/queue?niche=` (Sign in with CoinPay; operators by CoinPay `sub` allowlist, never email), `/p/:id` proposal. Installable.
48
+ - **HTTP API**: `/api/v1/solicitations?niche=in|out|all|<name>`, `/profile`, `/profile/search`, `/sources`, `/stats`; operator: `/interventions?niche=`, `/proposals/:id`, `/solicitations/:id/draft`, `/ingest/digest`, `/run/:job` (`profile`, `rescreen`), `POST /profile/crawl`, `POST /profile/pages`, `PUT /profile`. See `/docs`.
49
+ - **MCP**: streamable HTTP at `/mcp`: `search_solicitations` (niche filter), `get_solicitation`, `list_sources`, `stats`, `get_profile`, `search_profile_pages`; operator (Bearer key): `list_interventions`, `get_proposal`, `resolve_intervention`, `draft_proposal`, `ingest_digest`, `crawl_profile`, `update_profile`.
50
+ - **CLI + TUI**: `npx @profullstack/gov-contracts search software --niche "Agentic engineering"`, `niches`, `site <words>`, `profile crawl|set|rescreen`, `queue`, `card`, `done`, `tui`, `mcp` (stdio bridge), `serve`.
38
51
 
39
52
  Public reads: 60 a minute free, then a $1 USDC day pass (CoinPay / x402). Operators are not metered.
40
53
 
@@ -56,6 +69,8 @@ DB_PATH=./data/gov.db OPERATOR_API_KEY=... C0MPUTE_API_KEY=... node src/server.j
56
69
  | `SAM_API_KEY` | optional: official SAM.gov API |
57
70
  | `COINPAY_X402_KEY`, `CRAWL_PAY_TO` | paid day pass past the free rate |
58
71
  | `DRAFT_MIN_FIT` (60), `DECIDE_MIN_FIT` (40) | thresholds |
72
+ | `PROFILE_DOMAIN` (profullstack.com), `PROFILE_MAX_PAGES` (40), `PROFILE_EVERY` (7d), `PROFILE_DISABLED` | the website the niches are read from |
73
+ | `C0MPUTE_JOBS_URL`, `C0MPUTE_JOBS_TOKEN` / `C0MPUTE_CRAWL_CLI=1`, `C0MPUTE_CRAWL_TIMEOUT_MS` (25000), `C0MPUTE_CRAWL_MAX_PRICE` (0.01) | spider through c0mpute `crawl.fetch`; `C0MPUTE_CRAWL=0` reads directly |
59
74
 
60
75
  Deploy: `sh deploy/deploy.sh` (c0mpute Apps, state in `/data`).
61
76
 
@@ -44,12 +44,18 @@ const stdin = async () => {
44
44
 
45
45
  const HELP = `gov-contracts: government contract opportunities, read and drafted. Submitting stays human.
46
46
 
47
- gov-contracts search [words] [--level federal|state|county|city] [--source sam|lacounty|digest] [--order fit|due|new] [--limit N]
47
+ gov-contracts search [words] [--niche in|out|all|<name>] [--level federal|state|county|city] [--source sam|lacounty|digest] [--order fit|due|new|niche] [--limit N]
48
+ gov-contracts niches our niche profile (read from our website) and bids per niche
49
+ gov-contracts site <words> search our indexed website pages
48
50
  gov-contracts show <id> one solicitation (e.g. sam:<notice id>, lacounty:50629)
49
51
  gov-contracts sources where opportunities come from
50
52
  gov-contracts stats
51
53
  operator (GOV_CONTRACTS_KEY):
52
- gov-contracts queue [--status open|done|dismissed|all]
54
+ gov-contracts queue [--status open|done|dismissed|all] [--niche in|all|<name>]
55
+ gov-contracts profile crawl [domain] [--pages 40] [--local] re-read the site; --local crawls from here
56
+ (c0mpute crawl.fetch via C0MPUTE_JOBS_URL or the c0mpute CLI, direct fallback)
57
+ gov-contracts profile set --niches '[{"name":"...","keywords":["..."]}]' | --naics 541511,541512 | --off "Niche name"
58
+ gov-contracts profile rescreen
53
59
  gov-contracts card <id> one card, with the text to copy
54
60
  gov-contracts done <id> [note] record that YOU did it (confirmation number, UEI...)
55
61
  gov-contracts dismiss <id> [note]
@@ -119,7 +125,7 @@ const commands = {
119
125
  async search() {
120
126
  const p = new URLSearchParams();
121
127
  if (pos.length) p.set('q', pos.join(' '));
122
- for (const k of ['level', 'source', 'order', 'limit']) if (flags[k]) p.set(k, flags[k]);
128
+ for (const k of ['level', 'source', 'order', 'limit', 'niche']) if (flags[k]) p.set(k, flags[k]);
123
129
  const rows = await call(`/api/v1/solicitations?${p}`);
124
130
  if (flags.json) return out(rows);
125
131
  rows.forEach((s) => console.log(line(s)));
@@ -136,9 +142,58 @@ const commands = {
136
142
  if (flags.json) return out(rows);
137
143
  rows.forEach((r) => console.log(`${r.gov_contracts ? '●' : '○'} ${r.name} [${r.level || ''}] ${r.gov_contracts ? r.gov_contracts.ingest : 'link only'}\n ${r.official_url || ''}`));
138
144
  },
145
+ async niches() {
146
+ const p = await call('/api/v1/profile');
147
+ if (flags.json) return out(p);
148
+ console.log(`${p.company} (${p.domain || 'no site'}) source: ${p.source}${p.method ? ` · ${p.method}` : ''}${p.crawled_at ? ` · read ${p.crawled_at.slice(0, 16)}` : ''} · ${p.indexed_pages} pages${p.crawling ? ` · reading ${p.crawling} now` : ''}\n${p.summary}\n`);
149
+ const counts = Object.fromEntries((p.niche_counts || []).map((r) => [r.niche, r.n]));
150
+ for (const n of p.niches) console.log(`${n.enabled === false ? '○' : '●'} ${n.name} (${counts[n.name] || 0} open bids)\n ${n.keywords.slice(0, 12).join(', ')}`);
151
+ console.log(`\nNAICS ${p.naics.join(', ')}`);
152
+ },
153
+ async site() {
154
+ const rows = await call(`/api/v1/profile/search?q=${encodeURIComponent(pos.join(' '))}`);
155
+ if (flags.json) return out(rows);
156
+ rows.forEach((r) => console.log(`${r.title || r.url}\n ${r.url}\n ${r.snippet}`));
157
+ if (!rows.length) console.log('No indexed page matches.');
158
+ },
159
+ async profile() {
160
+ const sub = pos[0] || 'show';
161
+ if (sub === 'show') return commands.niches();
162
+ if (sub === 'rescreen') return console.log(JSON.stringify(await call('/api/v1/run/rescreen', { method: 'POST' }), null, 2));
163
+ if (sub === 'crawl') {
164
+ const domain = pos[1] || (await call('/api/v1/profile')).domain;
165
+ const maxPages = Number(flags.pages || 40);
166
+ if (!flags.local) return console.log(JSON.stringify(await call('/api/v1/profile/crawl', { method: 'POST', body: { domain, max_pages: maxPages } }), null, 2));
167
+ if (!process.env.C0MPUTE_JOBS_URL && process.env.C0MPUTE_CRAWL_CLI === undefined) process.env.C0MPUTE_CRAWL_CLI = '1';
168
+ process.env.GOV_CONTRACTS_LOCAL = '1';
169
+ const { crawlSite, makePageFetcher } = await import('../src/spider.js');
170
+ const fetchPage = makePageFetcher();
171
+ console.error(`reading ${domain} (up to ${maxPages} pages; c0mpute ${fetchPage.mode || 'off'}, direct fallback)`);
172
+ const crawl = await crawlSite(domain, { maxPages, fetchPage, onPage: (p) => console.error(` ${p.via.padEnd(14)} ${p.url}`) });
173
+ for (const n of crawl.notes) console.error(` note: ${n}`);
174
+ if (!crawl.pages.length) throw new Error(`no readable pages: ${crawl.errors.map((e) => e.error).slice(0, 3).join('; ')}`);
175
+ console.error(`read ${crawl.pages.length} pages ${JSON.stringify(crawl.via)}; uploading`);
176
+ return console.log(JSON.stringify(await call('/api/v1/profile/pages', { method: 'POST', body: { domain, pages: crawl.pages } }), null, 2));
177
+ }
178
+ if (sub === 'set') {
179
+ const body = {};
180
+ if (flags.niches) body.niches = JSON.parse(flags.niches);
181
+ if (flags.naics) body.naics = String(flags.naics).split(',');
182
+ if (flags.negative) body.negative_keywords = String(flags.negative).split(',');
183
+ if (flags.off || flags.on) {
184
+ const cur = await call('/api/v1/profile');
185
+ const flip = (name, on) => { const n = cur.niches.find((x) => x.name.toLowerCase() === String(name).toLowerCase()); if (!n) throw new Error(`no niche named ${name}`); n.enabled = on; };
186
+ if (flags.off) flip(flags.off, false);
187
+ if (flags.on) flip(flags.on, true);
188
+ body.niches = cur.niches;
189
+ }
190
+ return console.log(JSON.stringify((await call('/api/v1/profile', { method: 'PUT', body })).screened, null, 2));
191
+ }
192
+ throw new Error('profile show | crawl [domain] [--local] | set ... | rescreen');
193
+ },
139
194
  async stats() { console.log(JSON.stringify(await call('/api/v1/stats'), null, 2)); },
140
195
  async queue() {
141
- const rows = await call(`/api/v1/interventions?status=${flags.status || 'open'}`);
196
+ const rows = await call(`/api/v1/interventions?status=${flags.status || 'open'}&niche=${encodeURIComponent(flags.niche || 'in')}`);
142
197
  if (flags.json) return out(rows);
143
198
  rows.forEach((iv) => console.log(`${iv.id} [${iv.kind}] ${iv.title.slice(0, 90)}${iv.due_at ? ` due ${String(iv.due_at).slice(0, 10)}` : ''}`));
144
199
  if (!rows.length) console.log('Nothing waiting.');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@profullstack/gov-contracts",
3
- "version": "0.1.0",
4
- "description": "Find government contract opportunities (SAM.gov, LA County, forwarded bid digests), read the RFP, score the fit, draft a proposal and queue every human step. Never submits anything on its own. API, CLI, MCP, TUI and PWA.",
3
+ "version": "0.2.0",
4
+ "description": "Find government contract opportunities (SAM.gov, LA County, forwarded bid digests), filter them by the niches read from your own website, read the RFP, score the fit, draft a proposal and queue every human step. Never submits anything on its own. API, CLI, MCP, TUI and PWA.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Profullstack, Inc.",
@@ -24,6 +24,9 @@
24
24
  "./digest": "./src/sources/digest.js",
25
25
  "./fit": "./src/fit.js",
26
26
  "./safety": "./src/safety.js",
27
+ "./niche": "./src/niche.js",
28
+ "./spider": "./src/spider.js",
29
+ "./profile": "./src/profile.js",
27
30
  "./server": "./src/app.js"
28
31
  },
29
32
  "files": ["bin", "src", "public", "README.md", "LICENSE"],
package/src/app.js CHANGED
@@ -6,13 +6,15 @@ import { SITE, me, mountAuth, operator } from './auth.js';
6
6
  import { aiStatus } from './ai.js';
7
7
  import { handleMcp, TOOL_NAMES } from './mcp.js';
8
8
  import {
9
- ICON, MANIFEST, SW, docsPage, homePage, messagePage, proposalPage, queuePage, solicitationPage, solicitationsPage,
9
+ ICON, MANIFEST, SW, docsPage, homePage, messagePage, profilePage, proposalPage, queuePage, solicitationPage, solicitationsPage,
10
10
  } from './pages.js';
11
+ import { applyPages, buildProfile, crawlRunning, getProfile, pagesFor, rescreen, saveProfile, searchPages } from './profile.js';
12
+ import { NICHE_LIBRARY } from './niche.js';
11
13
  import { getDaemon, ingestDigest, ingestSource, workTick } from './pipeline.js';
12
14
  import { publicSolicitation, startDraft } from './service.js';
13
15
  import { listSources } from './sources/index.js';
14
16
  import {
15
- documentsFor, getIntervention, getProposal, getSolicitation, latestProposal, listInterventions, openDb, resolveIntervention, searchSolicitations, stats,
17
+ documentsFor, getIntervention, getProposal, getSolicitation, latestProposal, listInterventions, logRun, nicheCounts, openDb, resolveIntervention, searchSolicitations, stats,
16
18
  } from './store.js';
17
19
  import { HUMAN_ONLY } from './safety.js';
18
20
  import { VERSION } from './version.js';
@@ -90,15 +92,16 @@ const needOperatorPage = async (c) => {
90
92
 
91
93
  app.get('/', (c) => {
92
94
  const isOp = !!operator(c);
93
- const top = searchSolicitations({ order: isOp ? 'fit' : 'new', limit: 12 }).map((s) => publicSolicitation(s, isOp));
95
+ const top = searchSolicitations({ order: isOp ? 'fit' : 'new', niche: 'in', limit: 12 }).map((s) => publicSolicitation(s, isOp));
94
96
  return html(c, homePage({ stats: stats(), top, signedIn: me(c), isOperator: isOp, error: c.req.query('signin_error') }));
95
97
  });
96
98
 
97
99
  app.get('/solicitations', (c) => {
98
100
  const isOp = !!operator(c);
99
101
  const { q, level, source } = c.req.query();
100
- const rows = searchSolicitations({ q, level, source, order: isOp ? 'fit' : 'due', limit: 200 }).map((s) => publicSolicitation(s, isOp));
101
- return html(c, solicitationsPage({ rows, q, level, source, signedIn: me(c), isOperator: isOp }));
102
+ const niche = c.req.query('niche') ?? 'in';
103
+ const rows = searchSolicitations({ q, level, source, niche, order: isOp ? 'fit' : 'due', limit: 200 }).map((s) => publicSolicitation(s, isOp));
104
+ return html(c, solicitationsPage({ rows, q, level, source, niche, niches: nicheCounts(), profile: getProfile(), signedIn: me(c), isOperator: isOp }));
102
105
  });
103
106
 
104
107
  app.get('/s/:id', async (c) => {
@@ -118,10 +121,12 @@ app.get('/queue', (c) => {
118
121
  const op = operator(c);
119
122
  if (!op) return needOperatorPage(c);
120
123
  const status = ['open', 'done', 'dismissed', 'all'].includes(c.req.query('status')) ? c.req.query('status') : 'open';
121
- const all = listInterventions({ status: 'all', limit: 500 });
124
+ const niche = c.req.query('niche') || 'in';
125
+ const all = listInterventions({ status: 'all', niche, limit: 500 });
122
126
  const counts = { open: 0, done: 0, dismissed: 0, all: all.length };
123
127
  for (const i of all) counts[i.status]++;
124
- return html(c, queuePage({ items: status === 'all' ? all : all.filter((i) => i.status === status), status, counts, account: op }));
128
+ const hidden = niche === 'all' ? 0 : listInterventions({ status, niche: 'all', limit: 500 }).length - (status === 'all' ? all.length : counts[status]);
129
+ return html(c, queuePage({ items: status === 'all' ? all : all.filter((i) => i.status === status), status, counts, niche, hidden, niches: nicheCounts(), profile: getProfile(), account: op }));
125
130
  });
126
131
 
127
132
  app.post('/queue/:id', async (c) => {
@@ -148,6 +153,43 @@ app.get('/p/:id', async (c) => {
148
153
  return html(c, proposalPage({ p, s: getSolicitation(p.solicitation_id), account: op }));
149
154
  });
150
155
 
156
+ app.get('/profile', (c) => {
157
+ const isOp = !!operator(c);
158
+ const p = getProfile();
159
+ return html(c, profilePage({ p, pages: pagesFor(p.domain || ''), running: crawlRunning(), library: NICHE_LIBRARY, isOperator: isOp, signedIn: me(c), notice: c.req.query('notice') }));
160
+ });
161
+
162
+ /** Start a crawl in the background; the page shows "reading" until it finishes. */
163
+ function startCrawl(domain, maxPages) {
164
+ if (crawlRunning()) return { status: 'already running', domain: crawlRunning() };
165
+ buildProfile(domain, { maxPages }).catch((e) => console.error('profile crawl failed', String(e?.message || e).slice(0, 200)));
166
+ return { status: 'crawling', domain, note: 'Reading the site, then deriving niches (1-5 minutes). GET /api/v1/profile for the result.' };
167
+ }
168
+
169
+ app.post('/profile', async (c) => {
170
+ if (!operator(c)) return needOperatorPage(c);
171
+ const f = await c.req.parseBody({ all: true });
172
+ const one = (k) => (Array.isArray(f[k]) ? f[k][0] : f[k]);
173
+ if (one('action') === 'crawl') {
174
+ try { startCrawl(String(one('domain') || getProfile().domain || ''), Number(one('max_pages') || 40)); } catch (e) { return c.redirect(`/profile?notice=${encodeURIComponent(e.message)}`, 303); }
175
+ return c.redirect('/profile?notice=Reading+the+site', 303);
176
+ }
177
+ const cur = getProfile();
178
+ const on = new Set([].concat(f.enabled || []).map(String));
179
+ const niches = cur.niches.map((n, i) => ({ ...n, enabled: on.has(String(i)), keywords: String(one(`kw_${i}`) ?? n.keywords.join(', ')).split(',').map((x) => x.trim()).filter(Boolean) }));
180
+ const addName = String(one('new_name') || '').trim();
181
+ const addKw = String(one('new_keywords') || '').split(',').map((x) => x.trim()).filter(Boolean);
182
+ const lib = NICHE_LIBRARY.find((l) => l.name === addName);
183
+ if (addName && (addKw.length || lib)) niches.push({ name: addName, keywords: addKw.length ? addKw : lib.keywords, enabled: true });
184
+ const p = saveProfile({
185
+ ...cur, niches, source: cur.source?.startsWith('site:') ? `${cur.source}+edited` : cur.source,
186
+ naics: String(one('naics') ?? cur.naics.join(', ')).split(/[,\s]+/).filter(Boolean),
187
+ negative_keywords: String(one('negative') ?? cur.negative_keywords.join(', ')).split(',').map((x) => x.trim()).filter(Boolean),
188
+ });
189
+ const r = rescreen(p);
190
+ return c.redirect(`/profile?notice=${encodeURIComponent(`Saved. ${r.in_niche} of ${r.checked} open bids are in your niches (${r.entered} added, ${r.left} filtered out).`)}`, 303);
191
+ });
192
+
151
193
  app.get('/docs', (c) => html(c, docsPage({ signedIn: me(c) })));
152
194
 
153
195
  /* --------------------------------------------------------------------- API -- */
@@ -157,8 +199,8 @@ const needOp = (c) => json(c, { error: { code: 'operator_only', message: 'Send A
157
199
 
158
200
  app.get('/api/v1/solicitations', (c) => {
159
201
  const isOp = !!operator(c);
160
- const { q, level, source, order, limit, offset, status, min_fit } = c.req.query();
161
- const rows = searchSolicitations({ q, level, source, order: order || (isOp ? 'fit' : 'due'), limit, offset, status: isOp ? status : undefined, minFit: isOp && min_fit ? Number(min_fit) : null });
202
+ const { q, level, source, order, limit, offset, status, min_fit, niche } = c.req.query();
203
+ const rows = searchSolicitations({ q, level, source, niche, order: order || (isOp ? 'fit' : 'due'), limit, offset, status: isOp ? status : undefined, minFit: isOp && min_fit ? Number(min_fit) : null });
162
204
  return json(c, { data: rows.map((s) => publicSolicitation(s, isOp)), meta: { count: rows.length, version: VERSION } });
163
205
  });
164
206
  app.get('/api/v1/solicitations/:id', (c) => {
@@ -168,13 +210,40 @@ app.get('/api/v1/solicitations/:id', (c) => {
168
210
  const p = isOp ? latestProposal(s.id) : null;
169
211
  return json(c, { data: { ...publicSolicitation(s, isOp), documents: documentsFor(s.id, { withText: false }), ...(p ? { proposal: { id: p.id, version: p.version, status: p.status } } : {}) } });
170
212
  });
213
+ app.get('/api/v1/profile', (c) => {
214
+ const p = getProfile();
215
+ return json(c, { data: { ...p, crawling: crawlRunning(), niche_counts: nicheCounts(), ...(operator(c) ? { pages: pagesFor(p.domain || '') } : {}) } });
216
+ });
217
+ app.get('/api/v1/profile/search', (c) => json(c, { data: searchPages(c.req.query('q'), { limit: c.req.query('limit') }) }));
218
+ app.post('/api/v1/profile/crawl', async (c) => {
219
+ if (!operator(c)) return needOp(c);
220
+ const b = await c.req.json().catch(() => ({}));
221
+ try { return json(c, { data: startCrawl(String(b.domain || getProfile().domain || ''), Number(b.max_pages || 40)) }, 202); } catch (e) { return json(c, { error: { code: 'bad_request', message: e.message } }, 400); }
222
+ });
223
+ /** Pages read elsewhere (the CLI's local c0mpute spider): {domain, pages: [{url, title, description, headings, text, via}]}. */
224
+ app.post('/api/v1/profile/pages', async (c) => {
225
+ if (!operator(c)) return needOp(c);
226
+ const b = await c.req.json().catch(() => ({}));
227
+ const pages = Array.isArray(b.pages) ? b.pages.filter((p) => p && typeof p.url === 'string').slice(0, 200) : [];
228
+ if (!b.domain || !pages.length) return json(c, { error: { code: 'bad_request', message: 'Send {"domain": "...", "pages": [{"url", "title", "text", ...}]}' } }, 400);
229
+ if (crawlRunning()) return json(c, { error: { code: 'busy', message: `already reading ${crawlRunning()}` } }, 409);
230
+ try { return json(c, { data: await applyPages(String(b.domain), pages) }); } catch (e) { logRun('profile', false, String(e?.message || e).slice(0, 300)); return json(c, { error: { code: 'failed', message: String(e?.message || e).slice(0, 300) } }, 502); }
231
+ });
232
+ /** Edit: {niches?, naics?, negative_keywords?, not_a_fit?, summary?}. Re-screens open bids. */
233
+ app.put('/api/v1/profile', async (c) => {
234
+ if (!operator(c)) return needOp(c);
235
+ const b = await c.req.json().catch(() => ({}));
236
+ const cur = getProfile();
237
+ const p = saveProfile({ ...cur, ...['niches', 'naics', 'negative_keywords', 'not_a_fit', 'summary', 'capabilities', 'company'].reduce((a, k) => (b[k] !== undefined ? { ...a, [k]: b[k] } : a), {}), source: cur.source?.startsWith('site:') && !cur.source.endsWith('+edited') ? `${cur.source}+edited` : cur.source });
238
+ return json(c, { data: { profile: p, screened: rescreen(p) } });
239
+ });
171
240
  app.get('/api/v1/sources', async (c) => json(c, { data: await listSources() }));
172
241
  app.get('/api/v1/stats', (c) => json(c, { data: stats() }));
173
242
  app.get('/api/v1/rules', (c) => json(c, { data: { human_only: HUMAN_ONLY } }));
174
243
 
175
244
  app.get('/api/v1/interventions', (c) => {
176
245
  if (!operator(c)) return needOp(c);
177
- return json(c, { data: listInterventions({ status: c.req.query('status') || 'open', kind: c.req.query('kind') }) });
246
+ return json(c, { data: listInterventions({ status: c.req.query('status') || 'open', kind: c.req.query('kind'), niche: c.req.query('niche') || 'all' }) });
178
247
  });
179
248
  app.get('/api/v1/interventions/:id', (c) => {
180
249
  if (!operator(c)) return needOp(c);
@@ -217,7 +286,9 @@ app.post('/api/v1/run/:job', async (c) => {
217
286
  if (job === 'work') return json(c, { data: await workTick() });
218
287
  const m = /^ingest-(\w+)$/.exec(job);
219
288
  if (m) return json(c, { data: await ingestSource(m[1]) });
220
- return json(c, { error: { code: 'not_found', message: 'jobs: ingest-sam, ingest-lacounty, work' } }, 404);
289
+ if (job === 'profile') return json(c, { data: startCrawl(getProfile().domain || process.env.PROFILE_DOMAIN || 'profullstack.com', Number(process.env.PROFILE_MAX_PAGES || 40)) }, 202);
290
+ if (job === 'rescreen') return json(c, { data: rescreen() });
291
+ return json(c, { error: { code: 'not_found', message: 'jobs: ingest-sam, ingest-lacounty, work, profile, rescreen' } }, 404);
221
292
  } catch (e) {
222
293
  return json(c, { error: { code: 'job_failed', message: String(e?.message || e).slice(0, 300) } }, 502);
223
294
  }
package/src/fit.js CHANGED
@@ -8,65 +8,18 @@
8
8
  * score stands in, marked as such.
9
9
  */
10
10
  import { z } from 'zod';
11
+ import { activeProfile, nicheMatch, profileBrief } from './niche.js';
11
12
 
12
- /** Profullstack's capabilities (niche focus: software, security, automation, hardware rental). */
13
- export const PROFILE = {
14
- company: 'Profullstack, Inc.',
15
- summary:
16
- '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.',
17
- capabilities: [
18
- 'Custom software development (web, mobile, PWA, desktop), API and integration work',
19
- 'Case management, permitting, CRM and workflow systems: build, configure, integrate, migrate',
20
- 'Cybersecurity: vulnerability assessment, application security review, monitoring, incident response support',
21
- 'Automation: business process automation, AI agents, data pipelines, document processing',
22
- 'Cloud and hosting operations, DevOps, software maintenance and support',
23
- 'Hardware and compute rental: GPU and server capacity, on-demand',
24
- ],
25
- naics: ['541511', '541512', '541513', '541519', '518210', '541690', '541715', '532420'],
26
- not_a_fit: [
27
- 'construction, facilities, janitorial, landscaping, food, vehicles, medical or clinical services',
28
- 'physical goods resale that requires an authorized manufacturer reseller agreement the bidder does not hold',
29
- 'staffing-only contracts requiring on-site cleared personnel',
30
- ],
31
- };
32
-
33
- const STRONG = [
34
- 'software', 'saas', 'application development', 'app development', 'web application', 'mobile app', 'mobile application', 'apis?', 'system integration', 'integrations?',
35
- 'cybersecurity', 'cyber security', 'information security', 'penetration test(ing)?', 'pentest', 'vulnerability', 'security assessment', 'web application firewall', 'siem',
36
- 'automation', 'artificial intelligence', 'ai', 'machine learning', 'data analytics', 'data platform', 'chatbot',
37
- 'case management', 'permit(ting)? (management|system|software)', 'crm', 'licensing system', 'workflow',
38
- 'it services', 'information technology', 'it modernization', 'systems integrator', 'solutions integrator', 'devops', 'cloud', 'hosting', 'website', 'web portal',
39
- 'gpu', 'high performance computing', 'hpc', 'servicenow', 'erp', 'it support',
40
- ];
41
- const WEAK = ['computer', 'servers?', 'storage', 'network(ing)?', 'license', 'subscription', 'digital', 'database', 'technology', 'it'];
42
- const NEGATIVE = [
43
- 'construction', 'janitorial', 'custodial', 'landscap\\w*', 'roofing', 'paving', 'hvac', 'plumbing', 'electrical contractor', 'food', 'catering',
44
- 'vehicles?', 'tires', 'fuel', 'uniforms?', 'medical supplies', 'pharmacy', 'gift cards?', 'furniture', 'printing', 'asphalt', 'concrete',
45
- 'valves?', 'gaskets?', 'ammunition', 'aircraft parts', 'nsn', 'repair parts', 'dredging', 'demolition', 'mowing', 'towing', 'airplane', 'aircraft maintenance',
46
- 'transportation services', 'bus', 'housing', 'polygraph', 'psychiatric', 'psychological', 'sewing', 'water well', 'architectural', 'engineering services',
47
- ];
48
- const rx = (words) => words.map((w) => new RegExp(`\\b${w}\\b`, 'i'));
49
- const STRONG_RX = rx(STRONG);
50
- const WEAK_RX = rx(WEAK);
51
- const NEGATIVE_RX = rx(NEGATIVE);
13
+ /** The active niche profile (niche.js; derived from the bidder's website by profile.js). */
14
+ export const PROFILE = new Proxy({}, { get: (_, k) => activeProfile()[k] });
52
15
 
53
16
  /**
54
- * 0 = skip, higher = more likely a fit. Cheap and deterministic, whole words only.
55
- * Nothing passes without a strong keyword or one of our NAICS codes.
17
+ * 0 = skip, higher = more likely a fit. Cheap and deterministic, whole words
18
+ * only, against the active niche profile. Nothing passes without a niche
19
+ * keyword in the title or one of our NAICS codes.
56
20
  */
57
- export function prefilter({ title = '', description = '', naics = '' } = {}) {
58
- const head = String(title);
59
- const body = String(description).slice(0, 1500);
60
- const n = String(naics || '');
61
- const naicsHit = PROFILE.naics.some((c) => n.includes(c)) ? 4 : /^54151|^5182/.test(n) ? 3 : 0;
62
- const strongTitle = STRONG_RX.filter((r) => r.test(head)).length;
63
- const weakTitle = WEAK_RX.filter((r) => r.test(head)).length;
64
- const strongBody = STRONG_RX.filter((r) => !r.test(head) && r.test(body)).length;
65
- // Long notices carry boilerplate ("cloud", "workflow"): the body only counts when the title is about tech too.
66
- if (!strongTitle && !naicsHit && !(strongBody && weakTitle)) return 0;
67
- let score = strongTitle * 4 + strongBody * 2 + weakTitle + naicsHit;
68
- score -= NEGATIVE_RX.filter((r) => r.test(head)).length * 5;
69
- return Math.max(0, Math.min(score, 30));
21
+ export function prefilter(sol = {}, profile = activeProfile()) {
22
+ return nicheMatch(sol, profile).score;
70
23
  }
71
24
 
72
25
  export const FitSchema = z.object({
@@ -81,12 +34,8 @@ export const FitSchema = z.object({
81
34
  set_aside_ok: z.boolean().nullable().default(null),
82
35
  });
83
36
 
84
- const SYSTEM = `You are a capture manager deciding whether a small company should bid on a government solicitation.
85
- Company profile:
86
- ${PROFILE.summary}
87
- Capabilities:
88
- - ${PROFILE.capabilities.join('\n- ')}
89
- Not a fit: ${PROFILE.not_a_fit.join('; ')}.
37
+ const system = () => `You are a capture manager deciding whether a small company should bid on a government solicitation.
38
+ ${profileBrief()}
90
39
  Read the solicitation and documents. Be strict. Renewing or reselling a named product's licenses or maintenance needs an authorized reseller: score those under 40. Score 70+ only when the work is clearly something the company does and it can legally bid (set-asides, reseller authorizations, clearances, on-site requirements).
91
40
  List the mandatory requirements, every form or certification the buyer requires (ONLY names written in the text; never invent form names or numbers), and any vendor registration needed to bid (for example SAM.gov UEI, Cal eProcure supplier ID, the county's own vendor portal).
92
41
  Answer with JSON only.`;
@@ -161,7 +110,7 @@ export async function scoreFit(sol, docs, { ai, timeoutMs } = {}) {
161
110
  if (!ai) return keywordFit(sol);
162
111
  try {
163
112
  const r = await ai.generateObject({
164
- system: SYSTEM,
113
+ system: system(),
165
114
  user: fitPrompt(sol, docs),
166
115
  schema: FitSchema,
167
116
  jsonSchema: z.toJSONSchema(FitSchema),
package/src/index.js CHANGED
@@ -6,4 +6,7 @@ export { parseDigest, parseMyGovWatch } from './sources/digest.js';
6
6
  export { draftProposal, toMarkdown, vendorPortals, ProposalSchema } from './propose.js';
7
7
  export { ingestSource, ingestDigest, workTick, startDaemon } from './pipeline.js';
8
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';
9
12
  export { VERSION } from './version.js';
package/src/mcp.js CHANGED
@@ -11,8 +11,9 @@ import { bearerIsOperator } from './auth.js';
11
11
  import { listSources } from './sources/index.js';
12
12
  import { publicSolicitation, startDraft } from './service.js';
13
13
  import { ingestDigest } from './pipeline.js';
14
+ import { applyPages, buildProfile, crawlRunning, getProfile, rescreen, saveProfile, searchPages } from './profile.js';
14
15
  import {
15
- documentsFor, getProposal, getSolicitation, latestProposal, listInterventions, resolveIntervention, searchSolicitations, stats,
16
+ documentsFor, getProposal, getSolicitation, latestProposal, listInterventions, nicheCounts, resolveIntervention, searchSolicitations, stats,
16
17
  } from './store.js';
17
18
  import { VERSION } from './version.js';
18
19
 
@@ -23,6 +24,7 @@ const NEED_KEY = 'Operator tool: send the gov-contracts operator key as "Authori
23
24
  export const TOOL_NAMES = [
24
25
  'search_solicitations', 'get_solicitation', 'list_sources', 'stats',
25
26
  'list_interventions', 'get_proposal', 'resolve_intervention', 'draft_proposal', 'ingest_digest',
27
+ 'get_profile', 'search_profile_pages', 'crawl_profile', 'update_profile',
26
28
  ];
27
29
 
28
30
  export function buildMcpServer({ isOperator = false } = {}) {
@@ -44,13 +46,13 @@ export function buildMcpServer({ isOperator = false } = {}) {
44
46
  };
45
47
 
46
48
  server.registerTool('search_solicitations', {
47
- description: 'Open government solicitations. Filter by keyword, level (federal|state|county|city) and source (sam|lacounty|digest). Ordered by fit (operators) or due date.',
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.',
48
50
  inputSchema: {
49
51
  q: z.string().optional(), level: z.enum(['federal', 'state', 'county', 'city']).optional(), source: z.enum(['sam', 'lacounty', 'digest']).optional(),
50
- order: z.enum(['fit', 'due', 'new']).optional(), limit: z.number().int().min(1).max(100).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(),
51
53
  },
52
54
  annotations: { readOnlyHint: true },
53
- }, pub(({ q, level, source, order, limit }) => searchSolicitations({ q, level, source, order: order || (isOperator ? 'fit' : 'due'), limit: limit || 25 }).map((s) => publicSolicitation(s, isOperator))));
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))));
54
56
 
55
57
  server.registerTool('get_solicitation', {
56
58
  description: 'One solicitation by id (e.g. "sam:<notice id>", "lacounty:50629"), with the documents read for it.',
@@ -73,9 +75,9 @@ export function buildMcpServer({ isOperator = false } = {}) {
73
75
 
74
76
  server.registerTool('list_interventions', {
75
77
  description: 'Operator: the human intervention queue (cards a person must work).',
76
- inputSchema: { status: z.enum(['open', 'done', 'dismissed', 'all']).optional(), kind: z.string().optional() },
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"') },
77
79
  annotations: { readOnlyHint: true },
78
- }, op(({ status, kind }) => listInterventions({ status: status || 'open', kind }).map(({ copy_text, ...iv }) => ({ ...iv, has_copy_text: !!copy_text }))));
80
+ }, op(({ status, kind, niche }) => listInterventions({ status: status || 'open', kind, niche: niche || 'in' }).map(({ copy_text, ...iv }) => ({ ...iv, has_copy_text: !!copy_text }))));
79
81
 
80
82
  server.registerTool('get_proposal', {
81
83
  description: 'Operator: a proposal draft (markdown) by proposal id, or the latest for a solicitation id.',
@@ -106,6 +108,46 @@ export function buildMcpServer({ isOperator = false } = {}) {
106
108
  inputSchema: { text: z.string().max(200_000) },
107
109
  }, op(({ text: body }) => ingestDigest(body)));
108
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
+
109
151
  return server;
110
152
  }
111
153