@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/pages.js ADDED
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Server-rendered pages (no client framework). The queue cards follow myna's
3
+ * manual hand-off cards: what to do, the exact text to paste, a link to open,
4
+ * and Done / Dismiss with a note.
5
+ */
6
+ import { footerHtml } from '@profullstack/footer';
7
+ import { HUMAN_ONLY } from './safety.js';
8
+ import { SITE } from './auth.js';
9
+ import { VERSION } from './version.js';
10
+
11
+ const HOST = new URL(SITE).host;
12
+ export const h = (v) => String(v ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]);
13
+
14
+ let pitFooter = { html: '', at: 0 };
15
+ /** pit.world network footer (pit.world, *.pit.world and Moshpit names). Server-side, cached 1 h, 3 s timeout, nothing on error. */
16
+ async function pitWorldFooter() {
17
+ if (process.env.GOV_OFFLINE === '1') return '';
18
+ if (Date.now() - pitFooter.at < 3600_000) return pitFooter.html;
19
+ try {
20
+ const r = await fetch(`https://pit.world/snippets/footer.html?site=${encodeURIComponent(HOST)}`, { signal: AbortSignal.timeout(3000) });
21
+ if (r.ok) pitFooter = { html: await r.text(), at: Date.now() };
22
+ else pitFooter.at = Date.now() - 3000_000;
23
+ } catch {
24
+ pitFooter.at = Date.now() - 3000_000;
25
+ }
26
+ return pitFooter.html;
27
+ }
28
+
29
+ let ringFooter = { html: '', at: 0 };
30
+ /** Site links + the Profullstack webring row (server-rendered). */
31
+ async function siteFooter() {
32
+ if (ringFooter.html && Date.now() - ringFooter.at < 900_000) return ringFooter.html;
33
+ const fallback = '<footer class="foot"><p>gov.procurement · <a href="/docs">Docs</a> · <a href="/llms.txt">llms.txt</a></p></footer>';
34
+ if (process.env.GOV_OFFLINE === '1') return fallback;
35
+ try {
36
+ const html = await footerHtml({
37
+ site: SITE,
38
+ name: 'gov.procurement',
39
+ since: 2026,
40
+ links: [
41
+ { label: 'Docs', href: '/docs' },
42
+ { label: 'MCP', href: '/docs#mcp' },
43
+ { label: 'llms.txt', href: '/llms.txt' },
44
+ { label: 'Source', href: 'https://github.com/profullstack/gov-contracts' },
45
+ ],
46
+ });
47
+ ringFooter = { html, at: Date.now() };
48
+ } catch {
49
+ ringFooter = { html: fallback, at: Date.now() - 600_000 };
50
+ }
51
+ return ringFooter.html;
52
+ }
53
+
54
+ const CSS = `
55
+ :root{--bg:#0c0f14;--fg:#e8edf4;--mute:#97a3b3;--acc:#ffb547;--acc2:#6cc6ff;--card:#141922;--line:#263041;--ok:#5be08a;--bad:#ff7a7a}
56
+ @media (prefers-color-scheme: light){:root{--bg:#f7f8fb;--fg:#121722;--mute:#566173;--acc:#b86b00;--acc2:#0b6fb0;--card:#fff;--line:#dde3ec;--ok:#167a3e;--bad:#b42323}}
57
+ *{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
58
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
59
+ a{color:var(--acc2)}code,pre,textarea{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13.5px}
60
+ header.top,main{max-width:1100px;margin:0 auto;padding:0 16px}
61
+ header.top{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;padding-top:16px;padding-bottom:6px}
62
+ .brand{font-weight:800;font-size:20px;text-decoration:none;color:var(--fg)}.brand span{color:var(--acc)}
63
+ nav a{margin-left:14px;text-decoration:none}
64
+ h1{font-size:clamp(26px,4.6vw,42px);line-height:1.12;margin:26px 0 10px}h2{margin:28px 0 10px}
65
+ .lede{color:var(--mute);font-size:18px;max-width:780px}
66
+ .pill{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:1px 9px;font-size:12px;color:var(--mute);margin-right:4px}
67
+ .pill.fit{color:var(--bg);background:var(--acc);border-color:var(--acc);font-weight:700}
68
+ .stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin:18px 0}
69
+ .stat{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:12px}.stat b{display:block;font-size:26px}.stat span{color:var(--mute);font-size:13px}
70
+ table{border-collapse:collapse;width:100%;font-size:14px}td,th{border-bottom:1px solid var(--line);padding:8px;text-align:left;vertical-align:top}th{color:var(--mute);font-weight:600}
71
+ .tw{overflow-x:auto}
72
+ .cards{display:grid;gap:14px;margin:16px 0}
73
+ .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px}
74
+ .card .eyebrow{font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--acc);font-weight:700}
75
+ .card h3{margin:4px 0 8px;font-size:18px}.card .meta{color:var(--mute);font-size:13px;margin-bottom:8px}
76
+ .card ol,.card ul{margin:6px 0 10px 20px;padding:0}
77
+ .card textarea{width:100%;min-height:180px;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:10px;padding:10px}
78
+ .row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:8px}
79
+ button,.btn{background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:9px;padding:8px 13px;font:inherit;cursor:pointer;text-decoration:none;display:inline-block}
80
+ .btn.primary,button.primary{background:var(--acc);color:#111;border-color:var(--acc);font-weight:700}
81
+ input[type=text],input[type=search],select{background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font:inherit}
82
+ .note{color:var(--mute);font-size:14px}.warn{border-left:4px solid var(--acc);padding:8px 12px;background:var(--card);border-radius:8px}
83
+ .err{color:var(--bad)}.ok{color:var(--ok)}
84
+ pre{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;white-space:pre-wrap}
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}
89
+ `;
90
+
91
+ async function layout({ title, description, path = '/', signedIn = null }, body) {
92
+ const [site, pit] = await Promise.all([siteFooter(), pitWorldFooter()]);
93
+ const auth = signedIn ? `<a href="/queue">Queue</a><a href="/signout">Sign out</a>` : `<a href="/signin?next=/queue">Sign in with CoinPay</a>`;
94
+ return `<!doctype html>
95
+ <html lang="en">
96
+ <head>
97
+ <meta charset="utf-8">
98
+ <meta name="viewport" content="width=device-width, initial-scale=1">
99
+ <title>${h(title)}</title>
100
+ <meta name="description" content="${h(description)}">
101
+ <link rel="canonical" href="${h(SITE.replace(/\/$/, '') + path)}">
102
+ <meta property="og:title" content="${h(title)}"><meta property="og:description" content="${h(description)}"><meta property="og:site_name" content="gov.procurement">
103
+ <meta name="theme-color" content="#0c0f14">
104
+ <link rel="manifest" href="/manifest.webmanifest">
105
+ <link rel="icon" href="/icon.svg" type="image/svg+xml">
106
+ <link rel="alternate" type="text/plain" href="/llms.txt" title="llms.txt">
107
+ <style>${CSS}</style>
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>
109
+ </head>
110
+ <body>
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>
112
+ <main>${body}</main>
113
+ ${site}
114
+ ${pit}
115
+ <script>if('serviceWorker' in navigator)navigator.serviceWorker.register('/sw.js').catch(()=>{});</script>
116
+ </body>
117
+ </html>`;
118
+ }
119
+
120
+ /** Tiny markdown for card bodies: paragraphs, numbered and bullet lists. */
121
+ export function mdLite(text) {
122
+ const out = [];
123
+ let list = null;
124
+ const close = () => { if (list) { out.push(`</${list}>`); list = null; } };
125
+ for (const raw of String(text || '').split('\n')) {
126
+ const line = raw.trim();
127
+ const num = /^\d+\.\s+(.*)$/.exec(line);
128
+ const bul = /^[-*]\s+(.*)$/.exec(line);
129
+ if (num) { if (list !== 'ol') { close(); out.push('<ol>'); list = 'ol'; } out.push(`<li>${h(num[1])}</li>`); }
130
+ else if (bul) { if (list !== 'ul') { close(); out.push('<ul>'); list = 'ul'; } out.push(`<li>${h(bul[1])}</li>`); }
131
+ else if (!line) close();
132
+ else { close(); out.push(`<p>${h(line)}</p>`); }
133
+ }
134
+ close();
135
+ return out.join('');
136
+ }
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>` : '');
139
+ const fitPill = (s) => (s.fit_score != null ? `<span class="pill fit" title="fit score">${h(s.fit_score)}</span>` : '');
140
+ const due = (d) => (d ? h(String(d).slice(0, 10)) : '');
141
+
142
+ function solTable(rows, { showFit }) {
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>';
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
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>`)
146
+ .join('')}</tbody></table></div>`;
147
+ }
148
+
149
+ export async function homePage({ stats, top, signedIn, isOperator, error }) {
150
+ const body = `
151
+ ${error ? `<p class="warn err">${h(error)}</p>` : ''}
152
+ <h1>Government contracts, read and drafted. Submitted by a person.</h1>
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>
154
+ <div class="stats">
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>
157
+ <div class="stat"><b>${h(stats.by_status?.scored || 0)}</b><span>scored, not drafted</span></div>
158
+ <div class="stat"><b>${h(stats.drafts)}</b><span>proposal drafts</span></div>
159
+ <div class="stat"><b>${h(stats.interventions_open)}</b><span>waiting on a person</span></div>
160
+ </div>
161
+ <p class="warn"><b>Never automatic:</b> ${Object.values(HUMAN_ONLY).join('; ')}. Those are queue cards only.</p>
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>
164
+ ${solTable(top, { showFit: isOperator })}
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>
166
+ <h2>Every surface</h2>
167
+ <p>HTTP API at <code>/api/v1</code>, MCP at <code>/mcp</code>, CLI and TUI: <code>npx @profullstack/gov-contracts</code> (or <code>curl -fsSL ${h(SITE)}install.sh | sh</code>), and this page installs as an app. Public reads are free (60 a minute); past that a $1 USDC day pass over CoinPay / x402.</p>`;
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);
169
+ }
170
+
171
+ export async function solicitationsPage({ rows, q, level, source, niche = 'in', niches = [], profile, signedIn, isOperator }) {
172
+ const opt = (v, cur, label) => `<option value="${h(v)}"${v === cur ? ' selected' : ''}>${h(label)}</option>`;
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>
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>
177
+ <input type="search" name="q" value="${h(q || '')}" placeholder="software, permit, cybersecurity..." aria-label="Search">
178
+ <select name="level" aria-label="Level">${opt('', level || '', 'Any level')}${['federal', 'state', 'county', 'city'].map((l) => opt(l, level, l)).join('')}</select>
179
+ <select name="source" aria-label="Source">${opt('', source || '', 'Any source')}${['sam', 'lacounty', 'digest'].map((l) => opt(l, source, l)).join('')}</select>
180
+ <button class="primary">Search</button></form>
181
+ ${solTable(rows, { showFit: isOperator })}`;
182
+ return layout({ title: 'Open solicitations · gov.procurement', description: 'Open government contract opportunities.', path: '/solicitations', signedIn }, body);
183
+ }
184
+
185
+ export async function solicitationPage({ s, docs, proposal, isOperator, signedIn }) {
186
+ const contacts = (s.contacts || []).map((c) => `${h(c.name || '')}${c.email ? ` &lt;${h(c.email)}&gt;` : ''}${c.phone ? ` ${h(c.phone)}` : ''}`).join('<br>');
187
+ const fit = isOperator && s.fit
188
+ ? `<div class="card"><div class="eyebrow">Fit ${h(s.fit_score)}/100 · ${h(s.fit.verdict || '')} · ${h(s.fit.method || '')}</div><p>${h(s.fit.summary || '')}</p>
189
+ ${s.fit.why?.length ? `<b>Why</b><ul>${s.fit.why.map((x) => `<li>${h(x)}</li>`).join('')}</ul>` : ''}
190
+ ${s.fit.risks?.length ? `<b>Risks</b><ul>${s.fit.risks.map((x) => `<li>${h(x)}</li>`).join('')}</ul>` : ''}
191
+ ${s.fit.requirements?.length ? `<b>Requirements</b><ul>${s.fit.requirements.map((x) => `<li>${h(x)}</li>`).join('')}</ul>` : ''}
192
+ ${s.fit.forms?.length ? `<b>Forms</b><ul>${s.fit.forms.map((x) => `<li>${h(x)}</li>`).join('')}</ul>` : ''}</div>`
193
+ : '';
194
+ const draftBtn = isOperator ? `<form method="post" action="/s/${encodeURIComponent(s.id)}/draft" class="row"><button class="primary">${proposal ? 'Draft again' : 'Draft a proposal'}</button>${proposal ? `<a class="btn" href="/p/${h(proposal.id)}">Proposal v${h(proposal.version)} (${h(proposal.status)})</a>` : ''}</form>` : '';
195
+ const body = `<p class="note"><a href="/solicitations">Solicitations</a> / ${h(s.source)}</p>
196
+ <h1>${h(s.title)}</h1>
197
+ <p><span class="pill">${h(s.level || '')}</span><span class="pill">${h(s.notice_type || 'notice')}</span>${s.set_aside ? `<span class="pill">${h(s.set_aside)}</span>` : ''}${s.naics ? `<span class="pill">NAICS ${h(s.naics)}</span>` : ''}</p>
198
+ <table><tbody>
199
+ <tr><th>Buyer</th><td>${h(s.agency || '')}</td></tr>
200
+ <tr><th>Number</th><td>${h(s.number || 'n/a')}</td></tr>
201
+ <tr><th>Due</th><td>${h(s.due_at || 'n/a')}</td></tr>
202
+ <tr><th>Official page</th><td>${s.url ? `<a href="${h(s.url)}" rel="noopener" target="_blank">${h(s.url)}</a>` : 'Not linked: find it on the buyer\'s procurement page.'}</td></tr>
203
+ ${contacts ? `<tr><th>Contacts</th><td>${contacts}</td></tr>` : ''}
204
+ </tbody></table>
205
+ ${fit}${draftBtn}
206
+ <h2>Notice</h2><pre>${h((s.description || '').slice(0, 8000))}</pre>
207
+ ${docs.length ? `<h2>Documents read</h2><ul>${docs.map((d) => `<li>${d.url ? `<a href="${h(d.url)}" rel="noopener" target="_blank">${h(d.name || d.url)}</a>` : h(d.name || '')} <span class="note">${h(d.kind)}${d.text_chars ? ` · ${h(d.text_chars)} chars read` : ''}${d.error ? ` · <span class="err">${h(d.error)}</span>` : ''}</span></li>`).join('')}</ul>` : ''}`;
208
+ return layout({ title: `${s.title} · gov.procurement`, description: `${s.agency || ''} solicitation ${s.number || ''}, due ${s.due_at || 'n/a'}.`, path: `/s/${encodeURIComponent(s.id)}`, signedIn }, body);
209
+ }
210
+
211
+ const KIND_LABEL = {
212
+ submit_proposal: 'Review and submit',
213
+ set_price: 'Set the price',
214
+ sign_or_certify: 'Sign / certify',
215
+ register_vendor: 'Vendor registration',
216
+ decide_bid: 'Bid or no bid',
217
+ configure_source: 'Source setup',
218
+ };
219
+
220
+ export function cardHtml(iv) {
221
+ const resolved = iv.status !== 'open';
222
+ return `<article class="card" id="iv-${h(iv.id)}">
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>
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>` : ''}
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>` : ''}
227
+ ${mdLite(iv.body)}
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>` : ''}
229
+ <div class="row">
230
+ ${iv.copy_text ? `<button type="button" data-copy="copy-${h(iv.id)}">Copy</button>` : ''}
231
+ ${iv.open_url ? `<a class="btn" href="${h(iv.open_url)}" target="_blank" rel="noopener">Open</a>` : ''}
232
+ ${iv.kind === 'decide_bid' && !resolved ? `<form method="post" action="/s/${encodeURIComponent(iv.solicitation_id)}/draft"><button class="primary">Draft it</button></form>` : ''}
233
+ </div>
234
+ ${resolved ? `<p class="note">${h(iv.status)} ${iv.resolved_at ? h(iv.resolved_at.slice(0, 16).replace('T', ' ')) : ''}${iv.note ? `: ${h(iv.note)}` : ''}</p>
235
+ <form method="post" action="/queue/${h(iv.id)}"><input type="hidden" name="status" value="open"><button>Reopen</button></form>` : `<form method="post" action="/queue/${h(iv.id)}" class="row">
236
+ <input type="text" name="note" placeholder="${iv.kind === 'submit_proposal' ? 'Confirmation number' : iv.kind === 'register_vendor' ? 'UEI / vendor number' : 'Note'}" aria-label="Note" style="flex:1;min-width:200px">
237
+ <button class="primary" name="status" value="done">Mark done</button><button name="status" value="dismissed">Dismiss</button></form>`}
238
+ </article>`;
239
+ }
240
+
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>`;
242
+
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>`;
247
+ const body = `<h1>Interventions</h1>
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>` : ''}
251
+ <div class="row">${tab('open', 'Open')}${tab('done', 'Done')}${tab('dismissed', 'Dismissed')}${tab('all', 'All')}</div>
252
+ <div class="cards">${items.length ? items.map(cardHtml).join('') : '<p class="note">Nothing waiting on you.</p>'}</div>${COPY_JS}`;
253
+ return layout({ title: 'Queue · gov.procurement', description: 'Human intervention queue.', path: '/queue', signedIn: account }, body);
254
+ }
255
+
256
+ export async function proposalPage({ p, s, account }) {
257
+ const body = `<p class="note"><a href="/s/${encodeURIComponent(s.id)}">${h(s.title)}</a> / proposal v${h(p.version)}</p>
258
+ <h1>Proposal draft v${h(p.version)} <span class="pill">${h(p.status)}</span></h1>
259
+ <p class="note">${h(p.body?.method === 'template' ? 'Template (no AI answer)' : `AI draft${p.provider ? ` via ${p.provider}` : ''}`)} · ${h(p.created_at.slice(0, 16).replace('T', ' '))} · <a href="/p/${h(p.id)}.md">Download .md</a></p>
260
+ <div class="row"><button type="button" data-copy="pmd">Copy markdown</button></div>
261
+ <textarea id="pmd" readonly style="width:100%;min-height:70vh;background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:10px;padding:12px">${h(p.markdown)}</textarea>${COPY_JS}`;
262
+ return layout({ title: `Proposal: ${s.title}`, description: 'Proposal draft', path: `/p/${p.id}`, signedIn: account }, body);
263
+ }
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
+
294
+ export async function messagePage({ title, message, signedIn, status = 200 }) {
295
+ return { status, html: await layout({ title: `${title} · gov.procurement`, description: title, signedIn }, `<h1>${h(title)}</h1><p class="lede">${message}</p>`) };
296
+ }
297
+
298
+ export const MCP_TOOLS_DOC = [
299
+ ['search_solicitations', 'Open solicitations by keyword, level, source; best fit first.'],
300
+ ['get_solicitation', 'One solicitation with its documents (and fit, for operators).'],
301
+ ['list_sources', 'Datamart contract sources joined with what gov-contracts reads.'],
302
+ ['stats', 'Counts by status, source and level; last runs.'],
303
+ ['list_interventions', 'Operator: the human queue.'],
304
+ ['get_proposal', 'Operator: a proposal draft as markdown.'],
305
+ ['resolve_intervention', 'Operator: mark a card done or dismissed (records what a PERSON did).'],
306
+ ['draft_proposal', 'Operator: queue a (re)draft for a solicitation.'],
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.'],
312
+ ];
313
+
314
+ export async function docsPage({ signedIn }) {
315
+ const body = `<h1>Docs</h1>
316
+ <p class="lede">gov.procurement is the hosted @profullstack/gov-contracts (v${h(VERSION)}). It reads public bid sources, never writes to them, and never submits, registers, signs, prices or emails anyone.</p>
317
+ <h2 id="pipeline">Pipeline</h2>
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>
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>
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>
322
+ <li><b>Draft</b> (fit 60+): cover letter, technical approach, compliance matrix, forms checklist, pricing structure with every number blank.</li>
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>
324
+ <h2 id="api">HTTP API</h2>
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
328
+ GET /api/v1/solicitations/:id
329
+ GET /api/v1/sources
330
+ GET /api/v1/stats
331
+ # operator (Authorization: Bearer &lt;OPERATOR_API_KEY&gt; or a signed-in operator)
332
+ GET /api/v1/interventions?status=open|done|dismissed|all
333
+ POST /api/v1/interventions/:id {"status":"done"|"dismissed"|"open","note":"..."}
334
+ GET /api/v1/proposals/:id (?format=md)
335
+ POST /api/v1/solicitations/:id/draft
336
+ POST /api/v1/ingest/digest {"text":"...forwarded digest body..."}
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>
341
+ <h2 id="mcp">MCP</h2>
342
+ <p>Streamable HTTP at <code>${h(SITE)}mcp</code>. Operator tools need the Bearer key on the connection.</p>
343
+ <table><tbody>${MCP_TOOLS_DOC.map(([n, d]) => `<tr><td><code>${n}</code></td><td>${h(d)}</td></tr>`).join('')}</tbody></table>
344
+ <h2 id="cli">CLI and TUI</h2>
345
+ <pre>npx @profullstack/gov-contracts search software --level county
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
350
+ gov-contracts queue # needs GOV_CONTRACTS_KEY
351
+ gov-contracts done &lt;card-id&gt; "confirmation 12345"
352
+ gov-contracts digest &lt; digest.txt
353
+ gov-contracts tui # work the queue in a terminal
354
+ gov-contracts mcp # stdio MCP bridge to ${h(SITE)}mcp</pre>
355
+ <h2 id="limits">Limits and payment</h2>
356
+ <p>Free: 60 requests a minute per caller. Past that, a $1 day pass in USDC over CoinPay or x402. Operator calls are not metered.</p>`;
357
+ return layout({ title: 'Docs · gov.procurement', description: 'API, MCP, CLI and TUI for gov.procurement.', path: '/docs', signedIn }, body);
358
+ }
359
+
360
+ export const MANIFEST = {
361
+ name: 'gov.procurement',
362
+ short_name: 'gov.procurement',
363
+ description: 'Government contract opportunities, read and drafted; every submission stays a human step.',
364
+ start_url: '/queue',
365
+ scope: '/',
366
+ display: 'standalone',
367
+ background_color: '#0c0f14',
368
+ theme_color: '#0c0f14',
369
+ icons: [{ src: '/icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any maskable' }],
370
+ };
371
+
372
+ export const ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#0c0f14"/><path d="M32 10 54 20v4H10v-4zM14 27h6v18h-6zm11 0h6v18h-6zm11 0h6v18h-6zm11 0h6v18h-6zM10 48h44v6H10z" fill="#ffb547"/></svg>`;
373
+
374
+ /** Network-first for pages (so the queue is never stale), cache fallback offline. */
375
+ export const SW = `const C='gc-v${VERSION}';
376
+ self.addEventListener('install',e=>{self.skipWaiting();e.waitUntil(caches.open(C).then(c=>c.addAll(['/','/icon.svg','/manifest.webmanifest'])))});
377
+ self.addEventListener('activate',e=>e.waitUntil(caches.keys().then(ks=>Promise.all(ks.filter(k=>k!==C).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
378
+ self.addEventListener('fetch',e=>{const r=e.request;if(r.method!=='GET'||new URL(r.url).origin!==location.origin)return;
379
+ const p=new URL(r.url).pathname;const priv=/^\\/(api|queue|p|mcp|auth|signin|signout)(\\/|$)/.test(p);
380
+ e.respondWith(fetch(r).then(res=>{if(res.ok&&!priv){const cp=res.clone();caches.open(C).then(c=>c.put(r,cp))}return res}).catch(()=>caches.match(r).then(m=>m||caches.match('/'))))});`;
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The pipeline: ingest -> read the RFP -> score the fit -> draft -> queue.
3
+ * Scheduled by @profullstack/scraper-daemon (local engine, run records in the
4
+ * app's own SQLite: one process, no Redis on c0mpute Apps).
5
+ */
6
+ import { createDaemon, sqliteStore } from '@profullstack/scraper-daemon';
7
+ import { makeAi } from './ai.js';
8
+ import { ADAPTERS, adapterFor } from './sources/index.js';
9
+ import { parseDigest } from './sources/digest.js';
10
+ import { draftProposal, queueDecision } from './propose.js';
11
+ import { scoreFit } from './fit.js';
12
+ import { buildProfile, loadProfile, rescreen } from './profile.js';
13
+ import { USER_AGENT } from './http.js';
14
+ import {
15
+ documentsFor, dueFor, findFeedTwin, getSolicitation, logRun, openDb, saveDocument, setSolicitation, upsertSolicitation,
16
+ } from './store.js';
17
+
18
+ export const DRAFT_MIN = () => Number(process.env.DRAFT_MIN_FIT || 60);
19
+ export const DECIDE_MIN = () => Number(process.env.DECIDE_MIN_FIT || 40);
20
+
21
+ /** Store a batch of solicitations; counts of new/updated/same. */
22
+ export function store(list) {
23
+ const counts = { new: 0, updated: 0, same: 0 };
24
+ for (const s of list) counts[upsertSolicitation(s)]++;
25
+ return counts;
26
+ }
27
+
28
+ export async function ingestSource(name) {
29
+ const a = adapterFor(name);
30
+ if (!a?.ingest) throw new Error(`no scheduled ingest for ${name}`);
31
+ try {
32
+ const list = await a.ingest();
33
+ const counts = store(list);
34
+ logRun(`ingest:${name}`, true, { seen: list.length, ...counts });
35
+ return { source: name, seen: list.length, ...counts };
36
+ } catch (e) {
37
+ logRun(`ingest:${name}`, false, String(e?.message || e).slice(0, 300));
38
+ throw e;
39
+ }
40
+ }
41
+
42
+ /** Forwarded digest text -> solicitations. */
43
+ export async function ingestDigest(text, { ai = makeAi() } = {}) {
44
+ const { parser, solicitations } = await parseDigest(text, { ai });
45
+ // A bid we already read from the buyer's own feed is not added twice.
46
+ const twins = solicitations.map((s) => findFeedTwin(s.title)?.id).filter(Boolean);
47
+ const fresh = solicitations.filter((s) => !findFeedTwin(s.title));
48
+ const counts = store(fresh);
49
+ logRun('ingest:digest', true, { parser, seen: solicitations.length, already_in_feeds: twins.length, ...counts });
50
+ return { parser, seen: solicitations.length, already_in_feeds: twins.length, ...counts, ids: [...fresh.map((s) => `${s.source}:${s.ext_id}`), ...twins] };
51
+ }
52
+
53
+ /** Read one solicitation's documents. */
54
+ export async function readOne(sol) {
55
+ const a = adapterFor(sol.source);
56
+ const { docs, fields } = await a.readDocs(sol);
57
+ for (const d of docs) saveDocument(sol.id, d);
58
+ setSolicitation(sol.id, { ...fields, status: 'read', error: null });
59
+ }
60
+
61
+ /** Score one solicitation; drafts or asks a person depending on the score. */
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
+ }
68
+ const docs = documentsFor(sol.id);
69
+ const fit = await scoreFit(sol, docs, { ai });
70
+ setSolicitation(sol.id, { fit, fit_score: fit.score, status: 'scored' });
71
+ const fresh = getSolicitation(sol.id);
72
+ if (fit.method === 'ai' && fit.score >= DECIDE_MIN() && fit.score < DRAFT_MIN()) queueDecision(fresh);
73
+ if (fit.method !== 'ai' && fit.score >= DECIDE_MIN()) queueDecision(fresh);
74
+ return fit;
75
+ }
76
+
77
+ export async function draftOne(sol, { ai = makeAi() } = {}) {
78
+ return draftProposal(sol, documentsFor(sol.id), { ai });
79
+ }
80
+
81
+ /** Solicitations scored high enough by a model, not drafted yet. */
82
+ function readyToDraft(limit) {
83
+ return openDb().prepare(`SELECT id FROM solicitations WHERE status = 'scored' AND fit_score >= ? AND json_extract(fit, '$.method') = 'ai' AND niche_score > 0
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));
85
+ }
86
+
87
+ /** One pass of the work loop: read a few, score one, draft one. */
88
+ export async function workTick({ read = 3, score = 1, draft = 1 } = {}) {
89
+ const done = { read: 0, scored: 0, drafted: 0, errors: 0 };
90
+ for (const s of dueFor('new', read)) {
91
+ try { await readOne(s); done.read++; } catch (e) { done.errors++; setSolicitation(s.id, { status: 'error', error: String(e?.message || e).slice(0, 300) }); }
92
+ }
93
+ const ai = makeAi();
94
+ for (const s of dueFor('read', score)) {
95
+ try { await scoreOne(s, { ai }); done.scored++; } catch (e) { done.errors++; setSolicitation(s.id, { error: String(e?.message || e).slice(0, 300) }); }
96
+ }
97
+ for (const s of readyToDraft(draft)) {
98
+ try { await draftOne(s, { ai }); done.drafted++; } catch (e) { done.errors++; setSolicitation(s.id, { error: String(e?.message || e).slice(0, 300) }); }
99
+ }
100
+ if (done.read || done.scored || done.drafted || done.errors) logRun('work', done.errors === 0, done);
101
+ return done;
102
+ }
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
+
119
+ let daemon = null;
120
+
121
+ /** Start the scheduled updater (ingest every 6 h per source, work loop every minute). */
122
+ export function startDaemon() {
123
+ if (daemon || process.env.DAEMON_DISABLED === '1') return daemon;
124
+ bootProfile();
125
+ daemon = createDaemon({
126
+ name: 'gov-contracts',
127
+ store: sqliteStore(openDb(), { prefix: 'daemon' }),
128
+ concurrency: 2,
129
+ fetch: { userAgent: USER_AGENT, delayMs: 2000 },
130
+ });
131
+ for (const [name, a] of Object.entries(ADAPTERS)) {
132
+ if (!a.scheduled) continue;
133
+ daemon.job({ name: `ingest-${name}`, every: a.every, staleAfter: '1d', run: () => ingestSource(name) });
134
+ }
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() });
137
+ daemon.start();
138
+ return daemon;
139
+ }
140
+
141
+ export const getDaemon = () => daemon;