diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a3b862..99558ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,7 +58,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [api, browser, production] + suite: [api, browser, production, calibration, orchestration] steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: diff --git a/README.md b/README.md index 76d8604..07c2634 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ SyberLabs' job-search product: a private review workspace that remembers the rol - Exact draft acceptance: you approve specific wording; changing it requires review again. - Interview notes and follow-ups that do not reset a submitted or live-loop application. - Import a tracker CSV through column mapping and a record preview. Imported statuses stay research; existing Relay status and accepted drafts are preserved. +- A verified fact ledger and learned style rules that gate agent drafts at the API. Unsupported claims are refused, not queued. +- Batch review of logged drafts. Staging a draft does not accept it or send an application. +- Choose between real postings to set preferences, then plan the week to maximise the expected value of the best single offer. +- Pull public Greenhouse and Lever boards onto existing job identity. Discovery arrives Held. +- Record outcomes with a receipt before a submission counts toward reply rates. Ended applications cannot be reopened by import. - Explore fictional example records; no real applicant data is included. ## Integrations @@ -24,8 +29,10 @@ SyberLabs' job-search product: a private review workspace that remembers the rol - **[Claude](integrations/README.md)**: Draft preparation from your verified facts through the Claude API, using your own key. - **[Grok Bot](integrations/GROK_BOT.md)**: Validated research and draft file exchange inside the Bot's VM. - **[Tracker CSV](integrations/README.md)**: Map columns, preview rows, and import a local tracker file as research. +- **[Greenhouse](integrations/README.md)**: Read-only public board pull onto existing job identity. No credentials and no application sending. +- **[Lever](integrations/README.md)**: Read-only public board pull onto existing job identity. No credentials and no application sending. -You stay in control. Integrations are explicit file and command handoffs. Every returned draft needs human review. Relay does not send applications or sync accounts in the background. +You stay in control. Integrations are explicit file and command handoffs. Every returned draft needs human review. Agents cannot accept a draft or submit an application. Public board pulls are read-only. Relay does not send applications or sync accounts in the background. ChatGPT uses a prompt and file handoff; Codex also supports a local CLI adapter. This release does not include a hosted ChatGPT app or MCP connection. @@ -41,7 +48,7 @@ Relay is the workspace that remembers. Import research as evidence. Review the a - **Research keeps its history.** Matching posting URLs join the existing opportunity; changed source notes remain separate observations. Rediscovery preserves an existing interview or submitted status. - **Acceptance belongs to the text.** An imported Ready label does not approve a new draft. Accept it in Relay; changing the accepted text requires another review. - **Handoffs belong to a job and version.** Draft packets and editor checks reject stale work instead of silently replacing a newer review. -- **Bring the tools you already use.** ChatGPT, Codex, Claude, Grok Bot, Notion, Obsidian, and a tracker CSV can supply research and drafts. Relay keeps the review record across those handoffs. +- **Bring the tools you already use.** ChatGPT, Codex, Claude, Grok Bot, Notion, Obsidian, a tracker CSV, and public Greenhouse or Lever boards can supply research and drafts. Relay keeps the review record across those handoffs. Relay records acceptance inside its workspace. It does not send applications, verify every claim, or prove which words were submitted to an employer. URL matching cannot identify every repost across different job boards. @@ -84,6 +91,22 @@ Choose **Prepare for ChatGPT** or **Prepare for Codex** in **Connect your tools* The [GrokCell folder](grokcell/README.md) includes First Principles, Product Ideation, Red Flag, and Garbage Collector. These templates do not connect to Relay or grant access to application records. The [Relay adapter](integrations/GROK_BOT.md) remains the guide for exchanging job research and drafts. See also [context management](context-management/README.md). This is a pinned copy of the MIT-licensed [GrokCell project](https://github.com/sdcarlson/grokcell). +## Autonomy and review + +Relay separates what an agent may do freely from what only you may do. The split is enforced in the API, not in a prompt. + +The **fact ledger** (`/profile`) holds claims you have verified. Paste resume text to propose candidates; extraction writes nothing and marks nothing verified. A fact can carry an expiry for anything that goes stale, such as a current title or a headcount. + +The **style card** holds the voice rules learned from your corrections. The agent reads both through `relay_read_profile` and never writes either. + +A writing agent logs drafts through `relay_log_draft` at whatever volume it likes. Each sentence that asserts something checkable must cite a verified fact id, and every number must appear in a cited fact. A draft that fails either rule is refused at the API and is never written, so an invented achievement cannot reach a review queue. An agent short of a fact is expected to log with `confidence: "low"` rather than guess. + +Logged drafts accumulate until review is worth your time (`/review`). A session opens on the first draft in an unseen role cluster, on style drift within a proven one, on enough low-confidence drafts, or on a full batch — in that order. The session groups repeated habits so one decision covers several drafts, flags near-identical letters, and turns your corrections into style rules. Closing a session with no rules changes nothing about the next batch. + +Autonomy is then earned per role cluster. After enough reviewed drafts come back close to unchanged, a cluster graduates and its later drafts are placed into the matching job record unattended. Staging is not acceptance: status is untouched, `accepted_draft` is not set, and accepting an exact draft remains a human action in the workspace. A correction or an expired fact returns the cluster to full review. + +Relay still does not send applications. Nothing here submits, emails or messages anyone. + ## Run locally Node 24 and pnpm are required. From the repository root: @@ -101,6 +124,8 @@ pnpm build pnpm exec wrangler d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0000_sticky_robbie_robertson.sql pnpm exec wrangler d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0001_careless_leader.sql pnpm exec wrangler d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0002_job_key_observations.sql +pnpm exec wrangler d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0003_profile_calibration.sql +pnpm exec wrangler d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0004_selection_and_outcomes.sql pnpm dev ``` @@ -127,9 +152,27 @@ curl -sS http://127.0.0.1:8787/api/workspace \ The Sites plugin on `pnpm dev` strips caller-supplied `oai-authenticated-user-*` headers and injects the mock user only after the sign-in cookie. Header mock is for the built Worker. Production must use the Access gateway from the delivery foundation. +## Selection and outcomes + +Drafting well is not the largest lever. Which jobs you apply to is, because reply odds vary by orders of magnitude with fit while letter quality varies perhaps twofold. These stages address that. + +**Preferences** (`/preferences`) are elicited by forced choice over real postings, because people cannot state trade-off weights in the abstract but choose between two concrete jobs instantly. Around a dozen comparisons fit the five weights well enough to rank a large pool. Until you answer, Relay has no opinion and says so rather than inventing one. + +**The plan** (`/plan`) maximises the expected value of the *best single offer*, not the sum over applications, because you accept one job. That is an expected maximum, and computing it exactly produces a spread of odds on its own: once a likely offer is held, further similar roles add almost nothing and a long shot starts winning the comparison. No reach/match/floor ratio is hardcoded. Selection is greedy on gain per minute under the attention budget you set, and every row carries the reason it earned its place. + +**The read plane** pulls public Greenhouse and Lever boards through `board-pull`, normalising onto the same `jobKey` identity the workspace already uses. It reads only, needs no credentials and no account, and every posting arrives Held — discovery never implies a decision. + +**Outcomes** (`/track`) close the loop. Terminal states are local records of what actually happened and are deliberately not valid import statuses, so the existing import behaviour is unchanged and rediscovery can never reopen an application that has ended. A submission recorded here requires a receipt: the confirmation URL, reference or email subject. Imported submissions are kept and shown, but they arrive without a receipt and are excluded from the reply rates, because counting a send that may never have happened would corrupt every estimate built on it. + +Reply rates are reported as intervals with the evidence count that produced them, and they are descriptive. Samples are small, the market moves and a job search cannot be run as an experiment, so nothing here establishes that a change caused an outcome. + +**Interview preparation** falls out of the citation graph rather than being a separate feature: because every claim had to cite a verified fact, Relay already knows what each application commits you to defending. + +Relay still does not submit applications. There are no write-plane adapters in this release: nothing here fills in a form, sends an email, or messages anyone, and recording a submission is you telling Relay what you already did. + ## Integration boundaries -Connectors are local commands and explicit file import/export. Notion and Claude use your credentials. ChatGPT is a prompt/file handoff; Codex also supports a local CLI adapter; Grok Bot uses a documented command/file adapter. There is no automatic background sync, autonomous hunting, application sending, or LinkedIn messaging. Generated claims still require review. Production deployment and independent user adoption remain separate from this local workflow. +Connectors are local commands and explicit file import/export. Notion and Claude use your credentials. ChatGPT is a prompt/file handoff; Codex also supports a local CLI adapter; Grok Bot uses a documented command/file adapter. Agents may log and, for a graduated cluster, stage drafts; they cannot accept one or change an application status. Board pulls read public endpoints only and use no account identity. A recorded submission is your own report of something you did elsewhere and needs a receipt. Citation enforcement checks that a claim traces to a fact you verified; generated text still requires review. There is no automatic background sync, autonomous hunting, application sending, or LinkedIn messaging. Production deployment and independent user adoption remain separate from this local workflow. See [Local assisted browser trial](REVIEW.md#local-assisted-browser-trial) for the earlier `3b1efd7` read-only Notion, hand-transcribed Bot file, and browser acceptance, reload, and reimport evidence, still shown on a read-only reopen at `59ec7ac`. @@ -144,13 +187,18 @@ pnpm test pnpm exec tsc --noEmit pnpm lint pnpm public-copy:check +node tests/api.test.mjs +pnpm test:calibration +pnpm test:orchestration ``` The project, organization, personal profile, and website share one [maintained product description](docs/public-copy.json). [Public-copy process](docs/PUBLIC-COPY.md) explains generation, checks, and automatic refreshes. -API checks need a running local server and write only fictional test records. Connector tests mock vendor responses; they do not prove live account access. Domain, import, editor, and API tests cover status preservation, duplicate matching, exact acceptance, stale edits, and authentication rejection. +`pnpm test` is the unit gate. The API, calibration, and orchestration live suites each get a dedicated freshly migrated database via `pnpm test:api`, `pnpm test:calibration`, and `pnpm test:orchestration`. Do not run calibration and orchestration against the same D1: calibration graduates clusters and retires facts. Connector tests mock vendor responses; they do not prove live account access. + +For an existing local database still on migration 0001, apply 0002, then 0003 and 0004. From 0002, apply 0003 then 0004. From 0003, apply only 0004. Migration 0003 adds the fact ledger, style rules and draft-review tables. Migration 0004 adds preference, choice and outcome tables and defaulted posting columns on `jobs`; existing rows stay. Imported Ready is research evidence; a new record stays Held until its exact draft is accepted in Relay. -For an existing local database still on migration 0001, apply 0002 from the setup commands. Imported Ready is research evidence; a new record stays Held until its exact draft is accepted in Relay. +Domain, import, editor, profile, selection, and API tests cover status preservation, duplicate matching, exact acceptance, citation refusal, terminal outcomes that cannot be reopened by import, stale edits, and authentication rejection. ## Hosting and privacy diff --git a/app/agent-tools.ts b/app/agent-tools.ts index 3be3801..c194721 100644 --- a/app/agent-tools.ts +++ b/app/agent-tools.ts @@ -1,5 +1,35 @@ 'use client'; import { useEffect } from 'react'; +import { isTerminal } from '../lib/outcomes'; +type Json = Record; +type Tool = { + name: string; + description: string; + readOnly: boolean; + schema: Json; + run: (input: Json) => Promise; +}; +const object = (properties: Json, required: string[] = []) => ({ + type: 'object', + properties, + required, + additionalProperties: false, +}); +async function call(url: string, body?: Json) { + const r = await fetch( + url, + body + ? { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + } + : {}, + ); + const result = (await r.json()) as { error?: string }; + if (!r.ok) throw Error(result.error); + return result; +} export function useRelayTools(refresh: () => Promise) { useEffect(() => { const context = ( @@ -14,96 +44,123 @@ export function useRelayTools(refresh: () => Promise) { ).modelContext; if (!context?.registerTool) return; const lifecycle = new AbortController(); - for (const [name, description, action, readOnly] of [ - [ - 'relay_read_workspace', - 'Read opportunities, blockers and exact saved drafts. Does not modify records.', - null, - true, - ], - [ - 'relay_preview_import', - 'Check an array of research rows for duplicates without importing or changing records.', - 'preview', - true, - ], - [ - 'relay_stage_draft', - 'Save a draft for human review. Never accepts a draft or submits an application. Requires id, current version, draft and blocker.', - 'save', - false, - ], - ] as const) { - const inputSchema = - action === 'save' - ? { - type: 'object', - properties: { - id: { type: 'string' }, - version: { type: 'integer' }, - draft: { type: 'string' }, - blocker: { type: 'string' }, - }, - required: ['id', 'version', 'draft', 'blocker'], - additionalProperties: false, - } - : action === 'preview' - ? { - type: 'object', - properties: { - rows: { type: 'array', items: { type: 'object' } }, - }, - required: ['rows'], - additionalProperties: false, - } - : { type: 'object', properties: {}, additionalProperties: false }; + const tools: Tool[] = [ + { + name: 'relay_read_workspace', + description: + 'Read opportunities, blockers and exact saved drafts. Does not modify records.', + readOnly: true, + schema: object({}), + run: async () => ({ + jobs: ((await call('/api/workspace')) as { jobs: unknown }).jobs, + }), + }, + // The brief a writing agent works from: verified facts and the style + // rules learned so far. Read-only by design — an agent that can edit its + // own instructions drifts toward whatever is cheapest to generate. + { + name: 'relay_read_profile', + description: + 'Read the verified fact ledger and learned style rules that drafts must follow. Cite these fact ids when writing. Does not modify the profile.', + readOnly: true, + schema: object({}), + run: () => call('/api/profile'), + }, + { + name: 'relay_review_status', + description: + 'Read per-cluster trust, pending draft counts and whether a human review is due. Does not modify records.', + readOnly: true, + schema: object({}), + run: async () => { + const d = (await call('/api/drafts')) as Json; + return { trust: d.trust, trigger: d.trigger, batches: d.batches }; + }, + }, + { + name: 'relay_preview_import', + description: + 'Check an array of research rows for duplicates without importing or changing records.', + readOnly: true, + schema: object({ rows: { type: 'array', items: { type: 'object' } } }, [ + 'rows', + ]), + run: (input) => call('/api/workspace', { ...input, action: 'preview' }), + }, + // Logging is the autonomous path: unlimited volume, no human gate, but + // every factual claim must trace to a verified fact or the write is + // refused outright. + { + name: 'relay_log_draft', + description: + 'Log a written draft for later batch review. Every sentence making a factual claim must be supported by a cited verified fact id from relay_read_profile; unsupported claims are rejected. Set confidence "low" when a needed fact is missing instead of guessing. Never accepts or submits.', + readOnly: false, + schema: object( + { + job_id: { type: 'string' }, + body: { type: 'string' }, + cited: { type: 'array', items: { type: 'string' } }, + confidence: { type: 'string', enum: ['high', 'low'] }, + }, + ['job_id', 'body', 'cited'], + ), + run: async (input) => { + const result = await call('/api/drafts', { ...input, action: 'log' }); + await refresh(); + return result; + }, + }, + { + name: 'relay_stage_draft', + description: + 'Save a draft into a job record for human review. Never accepts a draft or submits an application. Requires id, current version, draft and blocker.', + readOnly: false, + schema: object( + { + id: { type: 'string' }, + version: { type: 'integer' }, + draft: { type: 'string' }, + blocker: { type: 'string' }, + }, + ['id', 'version', 'draft', 'blocker'], + ), + run: async (input) => { + const snapshot = (await call('/api/workspace')) as { + jobs: { id: string; status: string }[]; + }; + const job = snapshot.jobs.find((j) => j.id === input.id); + if (!job) throw Error('Record not found.'); + const status = + ['Submitted', 'Live loop'].includes(job.status) || + isTerminal(job.status) + ? job.status + : 'Held'; + const result = await call('/api/workspace', { + ...input, + action: 'save', + status, + }); + await refresh(); + return result; + }, + }, + ]; + for (const tool of tools) Promise.resolve( context.registerTool( { - name, - description, - inputSchema, - annotations: { readOnlyHint: readOnly, untrustedContentHint: true }, - async execute(input: Record) { - let status = 'Held'; - if (action === 'save') { - const snapshot = await fetch('/api/workspace'); - if (!snapshot.ok) throw Error('Sign in to stage a draft.'); - const data = (await snapshot.json()) as { - jobs: { id: string; status: string }[]; - }; - const job = data.jobs.find((j) => j.id === input.id); - if (!job) throw Error('Record not found.'); - if (['Submitted', 'Live loop'].includes(job.status)) - status = job.status; - } - const r = await fetch( - '/api/workspace', - action - ? { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - ...input, - action, - ...(action === 'save' ? { status } : {}), - }), - } - : {}, - ); - const result = (await r.json()) as { - error?: string; - jobs?: unknown; - }; - if (!r.ok) throw Error(result.error); - if (action === 'save') await refresh(); - return action ? result : { jobs: result.jobs }; + name: tool.name, + description: tool.description, + inputSchema: tool.schema, + annotations: { + readOnlyHint: tool.readOnly, + untrustedContentHint: true, }, + execute: tool.run, }, { signal: lifecycle.signal }, ), ).catch(() => console.warn('Relay agent tools could not register.')); - } return () => lifecycle.abort(); }, [refresh]); } diff --git a/app/api/drafts/route.ts b/app/api/drafts/route.ts new file mode 100644 index 0000000..582a7c8 --- /dev/null +++ b/app/api/drafts/route.ts @@ -0,0 +1,245 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { + clusterOf, + clusterTrust, + proposeRules, + reviewTrigger, + trustMap, + validateDraftLog, + validateRule, +} from '../../../lib/profile'; +import { + bumpProfile, + loadDrafts, + loadFacts, + profileVersion, +} from '../../../lib/store'; +export const dynamic = 'force-dynamic'; +const reply = (data: unknown, status = 200) => + Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +const stale = ( + facts: { status: string; expires: string | null }[], + now: string, +) => + facts.some((f) => f.status === 'Verified' && !!f.expires && f.expires <= now); +export async function GET() { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in to open your drafts.' }, 401); + const db = database(), + now = new Date().toISOString(); + const [drafts, facts] = await Promise.all([ + loadDrafts(db, user), + loadFacts(db, user), + ]); + const batches = await db + .prepare( + 'SELECT * FROM review_batches WHERE owner=? ORDER BY opened DESC LIMIT 50', + ) + .bind(user) + .all(); + return reply({ + drafts, + batches: batches.results, + trust: trustMap(drafts, stale(facts, now)), + trigger: reviewTrigger(drafts), + }); +} +export async function POST(request: Request) { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in first.' }, 401); + const origin = request.headers.get('origin'); + if (origin && origin !== new URL(request.url).origin) + return reply({ error: 'Invalid request origin.' }, 403); + try { + if (Number(request.headers.get('content-length') || 0) > 2000000) + return reply({ error: 'Request too large.' }, 413); + const raw = await request.text(); + if (raw.length > 2000000) + return reply({ error: 'Request too large.' }, 413); + const b = JSON.parse(raw), + db = database(), + now = new Date().toISOString(); + // The agent-facing write. A draft that cites an unverified fact, or makes a + // claim no cited fact supports, is refused here rather than queued for a + // reviewer to catch. + if (b.action === 'log') { + const job = await db + .prepare( + 'SELECT id,name,status,version,accepted_draft FROM jobs WHERE id=? AND owner=?', + ) + .bind(b.job_id, user) + .first<{ + id: string; + name: string; + status: string; + version: number; + accepted_draft: string | null; + }>(); + if (!job) return reply({ error: 'Record not found.' }, 404); + const facts = await loadFacts(db, user); + const entry = validateDraftLog(b, facts, now); + const cluster = clusterOf(job.name), + version = await profileVersion(db, user), + existing = await loadDrafts(db, user); + const trust = clusterTrust(cluster, existing, stale(facts, now)); + const statements = [ + db + .prepare( + 'INSERT INTO drafts (id,owner,job_id,cluster,body,profile_version,cited,confidence,verdict,created) VALUES (?,?,?,?,?,?,?,?,?,?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + cluster, + entry.body, + version, + entry.cited.join(','), + entry.confidence, + 'Logged', + now, + ), + ]; + // A graduated cluster earns the right to place its draft in the + // workspace unattended. It still only stages: status is untouched and + // acceptance stays a human action on an exact version. + const staged = + trust.state === 'Graduated' && + entry.confidence === 'high' && + job.status === 'Held' && + !job.accepted_draft; + if (staged) { + statements.push( + db + .prepare( + "UPDATE jobs SET draft=?,version=version+1,updated=? WHERE id=? AND owner=? AND version=? AND status='Held'", + ) + .bind(entry.body, now, job.id, user, job.version), + db + .prepare( + 'INSERT INTO events (id,owner,job_id,kind,detail,created) VALUES (?,?,?,?,?,?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + 'Draft staged by agent', + JSON.stringify({ cluster, profile_version: version }), + now, + ), + ); + } + await db.batch(statements); + return reply({ + ok: true, + cluster, + staged, + trust: trust.state, + review: reviewTrigger([ + ...existing, + { + id: 'pending', + job_id: job.id, + cluster, + body: entry.body, + corrected: '', + cited: entry.cited.join(','), + confidence: entry.confidence, + verdict: 'Logged', + profile_version: version, + }, + ]), + }); + } + if (b.action === 'open-batch') { + const drafts = await loadDrafts(db, user); + const trigger = reviewTrigger(drafts); + if (!trigger) + return reply({ error: 'No drafts are waiting for review.' }, 400); + const id = crypto.randomUUID(); + await db.batch([ + db + .prepare( + 'INSERT INTO review_batches (id,owner,reason,opened,size) VALUES (?,?,?,?,?)', + ) + .bind(id, user, trigger.reason, now, trigger.ids.length), + db + .prepare( + "UPDATE drafts SET batch=? WHERE owner=? AND verdict='Logged' AND batch IS NULL", + ) + .bind(id, user), + ]); + return reply({ + ok: true, + id, + reason: trigger.reason, + size: trigger.ids.length, + }); + } + // A correction is a style signal first and a text fix second, so the + // generalisations offered back are computed from the edit itself. + if (b.action === 'correct') { + if (typeof b.corrected !== 'string' || b.corrected.length > 20000) + throw Error('Provide corrected text under 20000 characters.'); + const draft = await db + .prepare('SELECT * FROM drafts WHERE id=? AND owner=?') + .bind(b.id, user) + .first<{ body: string }>(); + if (!draft) return reply({ error: 'Draft not found.' }, 404); + await db + .prepare( + "UPDATE drafts SET corrected=?, verdict='Corrected' WHERE id=? AND owner=?", + ) + .bind(b.corrected, b.id, user) + .run(); + return reply({ + ok: true, + proposals: proposeRules(draft.body, b.corrected), + }); + } + if (b.action === 'accept') { + const result = await db + .prepare("UPDATE drafts SET verdict='Reviewed' WHERE id=? AND owner=?") + .bind(b.id, user) + .run(); + if (!result.meta.changes) + return reply({ error: 'Draft not found.' }, 404); + return reply({ ok: true }); + } + // Closing a batch is the point of the whole loop: it is where corrections + // become rules the next drafts are written under. + if (b.action === 'close-batch') { + const rules = Array.isArray(b.rules) ? b.rules.map(validateRule) : []; + if (rules.length > 20) throw Error('Add at most 20 rules in one review.'); + const statements = rules.map((r: { rule: string; scope: string }) => + db + .prepare( + 'INSERT INTO style_rules (id,owner,rule,scope,origin,created) VALUES (?,?,?,?,?,?) ON CONFLICT(owner,scope,rule) DO NOTHING', + ) + .bind(crypto.randomUUID(), user, r.rule, r.scope, String(b.id), now), + ); + statements.push( + db + .prepare( + "UPDATE drafts SET verdict='Reviewed' WHERE owner=? AND batch=? AND verdict='Logged'", + ) + .bind(user, b.id), + db + .prepare( + 'UPDATE review_batches SET closed=?, rules_added=? WHERE id=? AND owner=?', + ) + .bind(now, rules.length, b.id, user), + ); + if (rules.length) statements.push(bumpProfile(db, user, now)); + await db.batch(statements); + return reply({ ok: true, rules_added: rules.length }); + } + return reply({ error: 'Unknown action.' }, 400); + } catch (e) { + return reply( + { error: e instanceof Error ? e.message : 'Unable to complete request.' }, + 400, + ); + } +} diff --git a/app/api/outcomes/route.ts b/app/api/outcomes/route.ts new file mode 100644 index 0000000..e48ae6e --- /dev/null +++ b/app/api/outcomes/route.ts @@ -0,0 +1,142 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { clusterOf } from '../../../lib/profile'; +import { evidence, statusAfter, validateOutcome } from '../../../lib/outcomes'; +import { responseRate } from '../../../lib/scoring'; +import { + loadDrafts, + loadFacts, + loadJobs, + loadOutcomes, +} from '../../../lib/store'; +export const dynamic = 'force-dynamic'; +const reply = (data: unknown, status = 200) => + Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +export async function GET() { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in to see your outcomes.' }, 401); + const db = database(); + const [outcomes, jobs, drafts, facts] = await Promise.all([ + loadOutcomes(db, user), + loadJobs(db, user), + loadDrafts(db, user), + loadFacts(db, user), + ]); + const clusters = new Map(jobs.map((j) => [j.id, clusterOf(j.name)])); + const seen = evidence(outcomes, (id) => clusters.get(id) || 'general'); + // Interview preparation falls out of the citation graph rather than being a + // separate feature: because every claim had to cite a verified fact, the + // system already knows exactly what each application commits you to + // defending. The newest draft per job is the one that was actually sent. + const byFact = new Map(facts.map((f) => [f.id, f])); + const latest = new Map(); + for (const d of drafts) latest.set(d.job_id, d); + const active = jobs.filter((j) => + ['Ready', 'Submitted', 'Live loop', 'Offer'].includes(j.status), + ); + const prep = active.map((job) => { + const draft = latest.get(job.id); + const cited = (draft?.cited || '').split(',').filter(Boolean); + return { + id: job.id, + name: job.name, + status: job.status, + version: job.version, + receipt: job.receipt ?? null, + claims: cited + .map((id) => byFact.get(id)) + .filter(Boolean) + .map((f) => ({ id: f!.id, claim: f!.claim, evidence: f!.evidence })), + }; + }); + return reply({ + outcomes, + prep, + // Descriptive only. Small samples, heavy confounding and a moving market + // mean these rates describe what happened; they do not establish that any + // change caused it. + rates: Object.fromEntries( + Object.entries(seen).map(([cluster, e]) => [ + cluster, + { ...responseRate(e.sent, e.responses), responses: e.responses }, + ]), + ), + }); +} +export async function POST(request: Request) { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in first.' }, 401); + const origin = request.headers.get('origin'); + if (origin && origin !== new URL(request.url).origin) + return reply({ error: 'Invalid request origin.' }, 403); + try { + const b = JSON.parse(await request.text()), + db = database(), + now = new Date().toISOString(); + if (b.action !== 'record') return reply({ error: 'Unknown action.' }, 400); + const job = await db + .prepare('SELECT id,status,version FROM jobs WHERE id=? AND owner=?') + .bind(b.id, user) + .first<{ id: string; status: string; version: number }>(); + if (!job) return reply({ error: 'Record not found.' }, 404); + if (!Number.isInteger(b.version) || b.version !== job.version) + return reply( + { error: 'This record changed. Reload before recording.' }, + 409, + ); + const entry = validateOutcome(job, b); + const status = statusAfter(entry.kind) ?? job.status; + const result = await db.batch([ + db + .prepare( + 'UPDATE jobs SET status=?, receipt=COALESCE(?,receipt), version=version+1, updated=? WHERE id=? AND owner=? AND version=?', + ) + .bind(status, entry.receipt, now, job.id, user, job.version), + db + .prepare( + 'INSERT INTO outcomes (id,owner,job_id,kind,detail,receipt,occurred,created) SELECT ?,?,?,?,?,?,?,? WHERE changes()=1 AND EXISTS (SELECT 1 FROM jobs WHERE id=? AND owner=? AND version=? AND updated=?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + entry.kind, + entry.detail, + entry.receipt, + entry.occurred, + now, + job.id, + user, + job.version + 1, + now, + ), + db + .prepare( + 'INSERT INTO events (id,owner,job_id,kind,detail,created) SELECT ?,?,?,?,?,? WHERE changes()=1 AND EXISTS (SELECT 1 FROM jobs WHERE id=? AND owner=? AND version=? AND updated=?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + `Outcome: ${entry.kind}`, + JSON.stringify({ occurred: entry.occurred, receipt: entry.receipt }), + now, + job.id, + user, + job.version + 1, + now, + ), + ]); + if (!result[0].meta.changes) + return reply( + { error: 'This record changed. Reload before recording.' }, + 409, + ); + return reply({ ok: true, status }); + } catch (e) { + return reply( + { error: e instanceof Error ? e.message : 'Unable to complete request.' }, + 400, + ); + } +} diff --git a/app/api/plan/route.ts b/app/api/plan/route.ts new file mode 100644 index 0000000..cbcb9b6 --- /dev/null +++ b/app/api/plan/route.ts @@ -0,0 +1,115 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { clusterOf, usableFact } from '../../../lib/profile'; +import { corpusOf, fitWeights, normalise, utility } from '../../../lib/utility'; +import { + expectedMax, + freshness, + reason, + responseRate, + selectPortfolio, + tierOf, + type Candidate, +} from '../../../lib/scoring'; +import { evidence } from '../../../lib/outcomes'; +import { + loadChoices, + loadFacts, + loadJobs, + loadOutcomes, + loadPreferences, + toPosting, +} from '../../../lib/store'; +export const dynamic = 'force-dynamic'; +const reply = (data: unknown, status = 200) => + Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +export async function GET() { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in to see your plan.' }, 401); + const db = database(), + now = new Date().toISOString(); + const [prefs, choices, facts, jobs, outcomes] = await Promise.all([ + loadPreferences(db, user), + loadChoices(db, user), + loadFacts(db, user), + loadJobs(db, user), + loadOutcomes(db, user), + ]); + const weights = fitWeights( + choices.map((c) => JSON.parse(c.delta) as number[]), + ); + const corpus = corpusOf( + facts.filter((f) => usableFact(f, now)).map((f) => f.claim), + ); + const clusters = new Map(jobs.map((j) => [j.id, clusterOf(j.name)])); + const seen = evidence(outcomes, (id) => clusters.get(id) || 'general'); + // Only jobs still awaiting a decision are candidates. Anything submitted, + // skipped or ended is history, not this week's work. + const open = jobs.filter((j) => j.status === 'Held' || j.status === 'Ready'); + const utilities = normalise( + open.map((j) => utility(toPosting(j), weights, corpus)), + ); + const rates = new Map>(); + const candidates: Candidate[] = open.map((j, i) => { + const cluster = clusters.get(j.id) || 'general'; + const ev = seen[cluster] || { sent: 0, responses: 0 }; + const rate = responseRate(ev.sent, ev.responses); + rates.set(j.id, rate); + return { + job_key: j.job_key, + u: utilities[i], + p: rate.mean * freshness(j.posted, now), + effort: j.effort || 20, + }; + }); + const plan = selectPortfolio(candidates, prefs.minutes); + const byKey = new Map( + open.map((j, i) => [j.job_key, { job: j, u: utilities[i] }]), + ); + const detail = (c: Candidate) => { + const entry = byKey.get(c.job_key)!; + const rate = rates.get(entry.job.id)!; + return { + id: entry.job.id, + job_key: c.job_key, + name: entry.job.name, + company: entry.job.company, + status: entry.job.status, + cluster: clusters.get(entry.job.id), + u: Number(c.u.toFixed(3)), + p: Number(c.p.toFixed(4)), + tier: tierOf(c.p), + effort: c.effort, + evidence: rate.sent, + band: [Number(rate.low.toFixed(3)), Number(rate.high.toFixed(3))], + reason: reason(c, now, entry.job.posted), + }; + }; + const chosenKeys = new Set(plan.chosen.map((c) => c.job_key)); + return reply({ + minutes: prefs.minutes, + calibrated: choices.length, + weights, + spent: plan.spent, + expected: Number(plan.expected.toFixed(4)), + // What the same budget would buy if it simply took the highest utilities. + // Reported so the portfolio's advantage is visible rather than asserted. + naive: Number( + expectedMax( + [...candidates] + .sort((a, b) => b.u - a.u) + .reduce((acc, c) => { + const spent = acc.reduce((s, x) => s + x.effort, 0); + if (spent + c.effort <= prefs.minutes) acc.push(c); + return acc; + }, []), + ).toFixed(4), + ), + plan: plan.chosen.map(detail), + rest: candidates + .filter((c) => !chosenKeys.has(c.job_key)) + .sort((a, b) => b.u - a.u) + .slice(0, 25) + .map(detail), + }); +} diff --git a/app/api/preferences/route.ts b/app/api/preferences/route.ts new file mode 100644 index 0000000..7b2d172 --- /dev/null +++ b/app/api/preferences/route.ts @@ -0,0 +1,148 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { usableFact } from '../../../lib/profile'; +import { + corpusOf, + difference, + fitWeights, + nextPair, + pairKey, + vector, +} from '../../../lib/utility'; +import { + loadChoices, + loadFacts, + loadJobs, + loadPreferences, + toPosting, +} from '../../../lib/store'; +export const dynamic = 'force-dynamic'; +const reply = (data: unknown, status = 200) => + Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +// Preferences are fitted from the choice log every time rather than stored as +// a running estimate, so a mistaken answer can be dropped and the model simply +// refits. There are never more than a few dozen comparisons. +async function state(db: D1Database, user: string) { + const [prefs, choices, facts, jobs] = await Promise.all([ + loadPreferences(db, user), + loadChoices(db, user), + loadFacts(db, user), + loadJobs(db, user), + ]); + const now = new Date().toISOString(); + const corpus = corpusOf( + facts.filter((f) => usableFact(f, now)).map((f) => f.claim), + ); + const deltas = choices.map((c) => JSON.parse(c.delta) as number[]); + const weights = fitWeights(deltas); + const asked = new Set(choices.map((c) => pairKey(c.winner, c.loser))); + const pool = jobs.filter((j) => j.status === 'Held').map(toPosting); + return { prefs, choices, weights, corpus, asked, pool, now }; +} +export async function GET() { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in to set your preferences.' }, 401); + const db = database(); + const { prefs, choices, weights, corpus, asked, pool } = await state( + db, + user, + ); + const pair = nextPair(pool, weights, corpus, asked); + return reply({ + weights, + answered: choices.length, + minutes: prefs.minutes, + pool: pool.length, + // Twelve comparisons fit five weights well enough to rank thousands of + // postings; more is welcome but the plan does not wait for it. + target: 12, + pair: pair && { + a: pair.a, + b: pair.b, + }, + }); +} +export async function POST(request: Request) { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in first.' }, 401); + const origin = request.headers.get('origin'); + if (origin && origin !== new URL(request.url).origin) + return reply({ error: 'Invalid request origin.' }, 403); + try { + const b = JSON.parse(await request.text()), + db = database(), + now = new Date().toISOString(); + if (b.action === 'choose') { + if ( + typeof b.winner !== 'string' || + typeof b.loser !== 'string' || + b.winner === b.loser + ) + throw Error('A choice needs two different jobs.'); + if (Object.hasOwn(b, 'delta')) + throw Error('A choice is two jobs, not a comparison vector.'); + const { pool, corpus } = await state(db, user); + const winner = pool.find((p) => p.job_key === b.winner); + const loser = pool.find((p) => p.job_key === b.loser); + if (!winner || !loser) + throw Error('Those postings are no longer in the pool.'); + const delta = difference(vector(winner, corpus), vector(loser, corpus)); + await db.batch([ + db + .prepare( + 'INSERT INTO choices (id,owner,winner,loser,delta,created) VALUES (?,?,?,?,?,?)', + ) + .bind( + crypto.randomUUID(), + user, + b.winner, + b.loser, + JSON.stringify(delta), + now, + ), + db + .prepare( + 'INSERT INTO preferences (owner,weights,pairs,updated) VALUES (?,?,1,?) ON CONFLICT(owner) DO UPDATE SET pairs=preferences.pairs+1, updated=excluded.updated', + ) + .bind(user, '', now), + ]); + const after = await state(db, user); + await db + .prepare('UPDATE preferences SET weights=? WHERE owner=?') + .bind(JSON.stringify(Object.values(after.weights)), user) + .run(); + return reply({ ok: true, weights: after.weights }); + } + if (b.action === 'minutes') { + const minutes = Number(b.minutes); + if (!Number.isFinite(minutes) || minutes < 15 || minutes > 2400) + throw Error('Set between 15 and 2400 minutes a week.'); + await db + .prepare( + 'INSERT INTO preferences (owner,minutes,updated) VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET minutes=excluded.minutes, updated=excluded.updated', + ) + .bind(user, Math.round(minutes), now) + .run(); + return reply({ ok: true, minutes: Math.round(minutes) }); + } + // Preferences drift. Clearing the log refits from nothing rather than + // leaving stale weights in place under a new intention. + if (b.action === 'reset') { + await db.batch([ + db.prepare('DELETE FROM choices WHERE owner=?').bind(user), + db + .prepare( + "UPDATE preferences SET weights='', pairs=0, updated=? WHERE owner=?", + ) + .bind(now, user), + ]); + return reply({ ok: true }); + } + return reply({ error: 'Unknown action.' }, 400); + } catch (e) { + return reply( + { error: e instanceof Error ? e.message : 'Unable to complete request.' }, + 400, + ); + } +} diff --git a/app/api/profile/route.ts b/app/api/profile/route.ts new file mode 100644 index 0000000..5f49fd8 --- /dev/null +++ b/app/api/profile/route.ts @@ -0,0 +1,143 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { validateFact, validateRule, usableFact } from '../../../lib/profile'; +import { parseResume } from '../../../lib/resume'; +import { + bumpProfile, + loadFacts, + loadRules, + profileVersion, +} from '../../../lib/store'; +export const dynamic = 'force-dynamic'; +const reply = (data: unknown, status = 200) => + Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +export async function GET() { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in to open your profile.' }, 401); + const db = database(), + now = new Date().toISOString(); + const [facts, rules, version] = await Promise.all([ + loadFacts(db, user), + loadRules(db, user), + profileVersion(db, user), + ]); + return reply({ + facts, + rules, + version, + usable: facts.filter((f) => usableFact(f, now)).length, + }); +} +export async function POST(request: Request) { + const user = (await getChatGPTUser())?.userId; + if (!user) return reply({ error: 'Sign in first.' }, 401); + const origin = request.headers.get('origin'); + if (origin && origin !== new URL(request.url).origin) + return reply({ error: 'Invalid request origin.' }, 403); + try { + if (Number(request.headers.get('content-length') || 0) > 2000000) + return reply({ error: 'Request too large.' }, 413); + const raw = await request.text(); + if (raw.length > 2000000) + return reply({ error: 'Request too large.' }, 413); + const b = JSON.parse(raw), + db = database(), + now = new Date().toISOString(); + // Extraction only proposes. It writes nothing, so a noisy resume costs a + // review pass rather than a false fact in the ledger. + if (b.action === 'extract') + return reply({ candidates: parseResume(b.text) }); + if (b.action === 'propose') { + if (!Array.isArray(b.facts) || !b.facts.length || b.facts.length > 100) + throw Error('Propose between 1 and 100 facts.'); + const rows = b.facts.map(validateFact); + await db.batch( + rows.map((f: { claim: string; evidence: string; tag: string }) => + db + .prepare( + 'INSERT INTO profile_facts (id,owner,claim,evidence,tag,status,created) VALUES (?,?,?,?,?,?,?) ON CONFLICT(owner,claim) DO UPDATE SET evidence=excluded.evidence, tag=excluded.tag', + ) + .bind( + crypto.randomUUID(), + user, + f.claim, + f.evidence, + f.tag, + 'Proposed', + now, + ), + ), + ); + return reply({ ok: true, proposed: rows.length }); + } + // Verification is the only path to a usable fact, and it is always a + // human action on one specific claim. + if (b.action === 'verify') { + if (b.expires != null && Number.isNaN(Date.parse(String(b.expires)))) + throw Error('Use an ISO date for the expiry, or leave it empty.'); + const result = await db.batch([ + db + .prepare( + "UPDATE profile_facts SET status='Verified', verified=?, expires=? WHERE id=? AND owner=?", + ) + .bind( + now, + b.expires ? new Date(String(b.expires)).toISOString() : null, + b.id, + user, + ), + bumpProfile(db, user, now), + ]); + if (!result[0].meta.changes) + return reply({ error: 'Fact not found.' }, 404); + return reply({ ok: true }); + } + if (b.action === 'retire') { + const result = await db.batch([ + db + .prepare( + "UPDATE profile_facts SET status='Retired' WHERE id=? AND owner=?", + ) + .bind(b.id, user), + bumpProfile(db, user, now), + ]); + if (!result[0].meta.changes) + return reply({ error: 'Fact not found.' }, 404); + return reply({ ok: true }); + } + if (b.action === 'rule-add') { + const rule = validateRule(b); + await db.batch([ + db + .prepare( + 'INSERT INTO style_rules (id,owner,rule,scope,origin,created) VALUES (?,?,?,?,?,?) ON CONFLICT(owner,scope,rule) DO NOTHING', + ) + .bind( + crypto.randomUUID(), + user, + rule.rule, + rule.scope, + typeof b.origin === 'string' ? b.origin.slice(0, 80) : '', + now, + ), + bumpProfile(db, user, now), + ]); + return reply({ ok: true }); + } + if (b.action === 'rule-remove') { + await db.batch([ + db + .prepare('DELETE FROM style_rules WHERE id=? AND owner=?') + .bind(b.id, user), + bumpProfile(db, user, now), + ]); + return reply({ ok: true }); + } + return reply({ error: 'Unknown action.' }, 400); + } catch (e) { + return reply( + { error: e instanceof Error ? e.message : 'Unable to complete request.' }, + 400, + ); + } +} diff --git a/app/api/workspace/route.ts b/app/api/workspace/route.ts index 9d88fca..2909b97 100644 --- a/app/api/workspace/route.ts +++ b/app/api/workspace/route.ts @@ -18,6 +18,17 @@ import { export const dynamic = 'force-dynamic'; const reply = (data: unknown, status = 200) => Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); +// Optional posting attributes supplied by the read plane. Hand-written imports +// omit them, so every field coerces to a safe default rather than failing. +const text = (v: unknown) => (typeof v === 'string' ? v.slice(0, 300) : ''); +const money = (v: unknown) => + typeof v === 'number' && Number.isFinite(v) && v > 0 && v < 10_000_000 + ? Math.round(v) + : null; +const minutes = (v: unknown) => + typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 480 + ? Math.round(v) + : 20; export async function GET() { const user = (await getChatGPTUser())?.userId; if (!user) return reply({ error: 'Sign in to open your workspace.' }, 401); @@ -72,7 +83,7 @@ export async function POST(request: Request) { statements.push( db .prepare( - `INSERT INTO jobs (id,owner,job_key,name,url,status,blocker,draft,updated) VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,job_key) DO UPDATE SET status=CASE WHEN jobs.status='Live loop' OR excluded.status='Live loop' THEN 'Live loop' WHEN jobs.status='Submitted' OR excluded.status='Submitted' THEN 'Submitted' ELSE jobs.status END, blocker=CASE WHEN jobs.blocker='' AND jobs.status NOT IN ('Ready','Submitted','Live loop') THEN excluded.blocker ELSE jobs.blocker END, accepted_draft=CASE WHEN excluded.status IN ('Submitted','Live loop') THEN NULL ELSE jobs.accepted_draft END, version=jobs.version+1, updated=excluded.updated`, + `INSERT INTO jobs (id,owner,job_key,name,url,status,blocker,draft,updated,company,level,remote,comp_min,comp_max,location,posted,source,effort) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,job_key) DO UPDATE SET status=CASE WHEN jobs.status IN ('Offer','Accepted','Closed') THEN jobs.status WHEN jobs.status='Live loop' OR excluded.status='Live loop' THEN 'Live loop' WHEN jobs.status='Submitted' OR excluded.status='Submitted' THEN 'Submitted' ELSE jobs.status END, blocker=CASE WHEN jobs.blocker='' AND jobs.status NOT IN ('Ready','Submitted','Live loop') THEN excluded.blocker ELSE jobs.blocker END, accepted_draft=CASE WHEN excluded.status IN ('Submitted','Live loop') THEN NULL ELSE jobs.accepted_draft END, company=CASE WHEN excluded.company!='' THEN excluded.company ELSE jobs.company END, level=CASE WHEN excluded.level!='' THEN excluded.level ELSE jobs.level END, remote=CASE WHEN excluded.remote!='' THEN excluded.remote ELSE jobs.remote END, comp_min=COALESCE(excluded.comp_min,jobs.comp_min), comp_max=COALESCE(excluded.comp_max,jobs.comp_max), location=CASE WHEN excluded.location!='' THEN excluded.location ELSE jobs.location END, posted=COALESCE(excluded.posted,jobs.posted), source=CASE WHEN excluded.source!='' THEN excluded.source ELSE jobs.source END, effort=excluded.effort, version=jobs.version+1, updated=excluded.updated`, ) .bind( crypto.randomUUID(), @@ -85,6 +96,15 @@ export async function POST(request: Request) { (b.action === 'bootstrap' ? packets[key]?.blocker || '' : ''), b.action === 'bootstrap' ? packets[key]?.draft || '' : '', now, + text(r.company), + text(r.level), + text(r.remote), + money(r.comp_min), + money(r.comp_max), + text(r.location), + text(r.posted) || null, + text(r.source), + minutes(r.effort), ), ); statements.push( diff --git a/app/globals.css b/app/globals.css index 8542716..49aff8a 100644 --- a/app/globals.css +++ b/app/globals.css @@ -735,3 +735,302 @@ footer { overflow-wrap: anywhere; white-space: pre-wrap; } +.backlink { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + color: var(--muted); +} +.productpage .import h2 { + display: flex; + align-items: center; + gap: 8px; + margin-top: 0; + font-size: 20px; +} +.checkrow { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 8px 0; + border-top: 1px solid var(--line); + font-size: 14px; +} +.checkrow small { + display: block; + color: var(--muted); + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.04em; +} +.factrow { + border-top: 1px solid var(--line); + padding: 12px 0; + font-size: 14px; +} +.factrow > b { + margin-right: 8px; +} +.factrow small { + display: block; + color: var(--muted); + font-size: 12px; + margin-top: 3px; +} +.factrow .actions { + margin-top: 8px; + align-items: center; +} +.factrow input[type='date'], +.actions input { + border: 1px solid var(--line); + border-radius: 4px; + padding: 7px 9px; + background: #fff; +} +.actions .grow { + flex: 1; + min-width: 180px; +} +.draftrow { + border-top: 1px solid var(--line); + padding: 16px 0; +} +.drafthead { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; +} +.drafthead small { + color: var(--muted); + font-size: 12px; +} +.draftrow pre { + white-space: pre-wrap; + background: var(--paper); + border: 1px solid var(--line); + border-radius: 4px; + padding: 12px; + font: + 13px/1.6 Arial, + sans-serif; + max-height: 260px; + overflow: auto; +} +.draftrow textarea { + width: 100%; + min-height: 90px; + border: 1px solid var(--line); + border-radius: 4px; + padding: 10px; + margin-top: 8px; +} +.proposals { + margin-top: 10px; + padding: 12px; + border: 1px dashed var(--line); + border-radius: 4px; + background: var(--paper); + font-size: 14px; +} +.proposals b { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 8px; +} +.proposals .actions { + align-items: center; + gap: 8px; + margin-bottom: 6px; +} +.proposals .actions span { + flex: 1; +} +.report.warn { + border-color: #b0743a; + background: #fdf6ec; +} +.report.warn b { + display: flex; + align-items: center; + gap: 7px; +} +.badge.warnbadge { + background: #fdf6ec; + border-color: #b0743a; + color: #8a541f; +} + +.stats strong .of { + font-size: 15px; + color: var(--muted); + font-weight: 400; +} +.choicepair { + display: grid; + grid-template-columns: 1fr auto 1fr; + gap: 14px; + align-items: stretch; +} +.choicecard { + text-align: left; + border: 1px solid var(--line); + border-radius: 6px; + background: #fff; + padding: 18px; + display: flex; + flex-direction: column; + gap: 12px; +} +.choicecard:hover:not(:disabled) { + border-color: var(--accent); + box-shadow: 0 2px 10px rgba(24, 56, 46, 0.08); +} +.choicecard > b { + font-size: 16px; + line-height: 1.35; +} +.choicecard dl { + margin: 0; + display: grid; + gap: 7px; +} +.choicecard dl > div { + display: flex; + justify-content: space-between; + gap: 12px; + font-size: 13.5px; + border-top: 1px solid var(--line); + padding-top: 6px; +} +.choicecard dt { + color: var(--muted); +} +.choicecard dd { + margin: 0; + text-align: right; +} +.choicecard .pick { + margin-top: auto; + font-size: 13px; + color: var(--accent); + font-weight: 600; +} +.versus { + align-self: center; + color: var(--muted); + font-size: 13px; +} +.weightrow { + display: grid; + grid-template-columns: 78px 1fr 58px; + gap: 12px; + align-items: center; + padding: 7px 0; + font-size: 14px; +} +.weightrow .track { + height: 8px; + background: var(--line); + border-radius: 100px; + overflow: hidden; + display: flex; +} +.weightrow .fill { + background: var(--accent); + height: 100%; +} +.weightrow .fill.neg { + background: #b0743a; + margin-left: auto; +} +.weightrow b { + text-align: right; + font-variant-numeric: tabular-nums; + font-size: 13px; +} +.planrow { + border-top: 1px solid var(--line); + padding: 16px 0; +} +.planhead { + display: flex; + align-items: center; + gap: 9px; + flex-wrap: wrap; +} +.planhead .rank { + width: 22px; + height: 22px; + border-radius: 50%; + background: var(--accent); + color: #fff; + font-size: 12px; + display: grid; + place-items: center; + flex-shrink: 0; +} +.why { + font-size: 13.5px; + color: var(--muted); + margin: 7px 0; + display: flex; + align-items: center; + gap: 6px; +} +.planstats { + display: flex; + gap: 26px; + margin: 0; + flex-wrap: wrap; +} +.planstats dt { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.07em; + color: var(--muted); +} +.planstats dd { + margin: 2px 0 0; + font-size: 14px; + font-variant-numeric: tabular-nums; +} +.planstats dd small { + color: var(--muted); + font-variant-numeric: normal; +} +.badge.tier-reach { + border-color: #6b4fa8; + color: #57408a; + background: #efeaf8; +} +.badge.tier-match { + border-color: var(--accent); + color: var(--accent); + background: #e2ebe4; +} +.badge.tier-floor { + border-color: #4a7f9e; + color: #3b6880; + background: #e6f0f5; +} +.claimrow { + border-left: 3px solid var(--line); + padding: 8px 0 8px 13px; + margin: 8px 0; + font-size: 14px; +} +.claimrow small { + display: block; + color: var(--muted); + font-size: 12px; + margin-top: 2px; +} +@media (max-width: 650px) { + .choicepair { + grid-template-columns: 1fr; + } +} diff --git a/app/plan/page.tsx b/app/plan/page.tsx new file mode 100644 index 0000000..949a7b2 --- /dev/null +++ b/app/plan/page.tsx @@ -0,0 +1,200 @@ +'use client'; +import { useCallback, useEffect, useState } from 'react'; +import Link from 'next/link'; +import { ArrowLeft, Target, TrendingUp } from 'lucide-react'; +type Row = { + id: string; + job_key: string; + name: string; + company: string; + status: string; + cluster: string; + u: number; + p: number; + tier: string; + effort: number; + evidence: number; + band: [number, number]; + reason: string; +}; +type Plan = { + minutes: number; + calibrated: number; + spent: number; + expected: number; + naive: number; + plan: Row[]; + rest: Row[]; + error?: string; +}; +const pct = (n: number) => (n * 100).toFixed(1) + '%'; +function Job({ row, rank }: { row: Row; rank?: number }) { + return ( +
+
+ {rank !== undefined && {rank}} + {row.name} + {row.tier} + {row.cluster} +
+

{row.reason}

+
+
+
Value
+
{row.u.toFixed(2)}
+
+
+
Reply odds
+
+ {pct(row.p)} + + {row.evidence + ? ` from ${row.evidence} sent` + : ' prior, no evidence yet'} + +
+
+
+
Costs
+
{row.effort} min
+
+
+
+ ); +} +export default function PlanPage() { + const [plan, setPlan] = useState(null), + [message, setMessage] = useState(''), + [signedOut, setSignedOut] = useState(false); + const refresh = useCallback(async () => { + const r = await fetch('/api/plan'); + const data = (await r.json()) as Plan; + if (r.status === 401) { + setPlan(null); + setSignedOut(true); + return; + } + if (!r.ok) throw Error(data.error); + setPlan(data); + }, []); + useEffect(() => { + void Promise.resolve() + .then(() => refresh()) + .catch((e: Error) => setMessage(e.message)); + }, [refresh]); + if (signedOut) + return ( +
+

This week

+

Sign in to see your plan.

+ {/* oxlint-disable-next-line next/no-html-link-for-pages -- Sites authentication requires top-level navigation. */} + + Sign in with ChatGPT + +
+ ); + const lift = plan && plan.naive > 0 ? plan.expected / plan.naive - 1 : 0; + return ( +
+ + Workspace + +

THIS WEEK · WHAT TO ACTUALLY APPLY TO

+

A plan sized to your week, not a queue.

+

+ You accept one job, so this maximises the expected value of the best + offer you receive rather than the total across applications. That is why + a long shot can outrank a safer role you already have covered. +

+ {message && ( +
+ {message} +
+ )} +
+
+ Selected + + {(plan?.plan.length ?? 0).toString().padStart(2, '0')} + + Applications this week +
+
+ Attention spent + {plan?.spent ?? 0} + of {plan?.minutes ?? 0} minutes +
+
+ Expected best offer + {(plan?.expected ?? 0).toFixed(3)} + On the normalised value scale +
+
+ + + {lift > 0.005 + ? `${(lift * 100).toFixed(0)}% above ranking by value` + : 'Matches a plain value ranking here'} + + Same budget, portfolio instead of top-N +
+
+ + {plan && plan.calibrated < 12 && ( +
+ +
+ The value model is still thin. +

+ {plan.calibrated} comparisons recorded. Until there are around a + dozen, roles are ranked mostly on odds and cost rather than on + what you actually want. +

+
+ + Answer a few + +
+ )} + +
+

Apply to these

+

+ Chosen by marginal gain per minute. Each row says why it earned the + place, so a wrong call is arguable rather than opaque. +

+ {!plan?.plan.length && ( +

+ Nothing selected. Either there are no open roles in the workspace, + or every one costs more than the remaining budget. +

+ )} + {plan?.plan.map((row, i) => ( + + ))} +
+ + {plan && plan.rest.length > 0 && ( +
+

Considered, not selected

+

+ These lost on gain per minute this week — usually because something + already chosen covers the same outcome, or the cost is too high for + what it adds. +

+ {plan.rest.map((row) => ( + + ))} +
+ )} +
+ Relay / SyberLabs + Selection is the largest lever. This is it. +
+
+ ); +} diff --git a/app/preferences/page.tsx b/app/preferences/page.tsx new file mode 100644 index 0000000..1c45e08 --- /dev/null +++ b/app/preferences/page.tsx @@ -0,0 +1,287 @@ +'use client'; +import { useCallback, useEffect, useState } from 'react'; +import Link from 'next/link'; +import { ArrowLeft, RotateCcw, Scale, Timer } from 'lucide-react'; +import type { Posting, Weights } from '../../lib/utility'; +type Pair = { a: Posting; b: Posting }; +type State = { + weights: Weights; + answered: number; + minutes: number; + pool: number; + target: number; + pair: Pair | null; + error?: string; +}; +function band(min: number | null, max: number | null) { + if (!min && !max) return 'Compensation not published'; + const money = (n: number) => '$' + Math.round(n / 1000) + 'k'; + return max && min ? `${money(min)} – ${money(max)}` : money((max ?? min)!); +} +function Card({ + posting, + onPick, + disabled, +}: { + posting: Posting; + onPick: () => void; + disabled: boolean; +}) { + return ( + + ); +} +export default function Preferences() { + const [state, setState] = useState(null), + [busy, setBusy] = useState(false), + [message, setMessage] = useState(''), + [minutes, setMinutes] = useState(120), + [signedOut, setSignedOut] = useState(false); + const refresh = useCallback(async () => { + const r = await fetch('/api/preferences'); + const data = (await r.json()) as State; + if (r.status === 401) { + setState(null); + setSignedOut(true); + return; + } + if (!r.ok) throw Error(data.error); + setState(data); + setMinutes(data.minutes); + }, []); + useEffect(() => { + void Promise.resolve() + .then(() => refresh()) + .catch((e: Error) => setMessage(e.message)); + }, [refresh]); + async function post(body: Record, note = '') { + setBusy(true); + try { + const r = await fetch('/api/preferences', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const data = (await r.json()) as { error?: string }; + if (!r.ok) throw Error(data.error); + await refresh(); + setMessage(note); + } catch (e) { + setMessage(e instanceof Error ? e.message : 'Unable to save.'); + } finally { + setBusy(false); + } + } + if (signedOut) + return ( +
+

Preferences

+

Sign in to set what a job is worth to you.

+ {/* oxlint-disable-next-line next/no-html-link-for-pages -- Sites authentication requires top-level navigation. */} + + Sign in with ChatGPT + +
+ ); + const answered = state?.answered ?? 0, + target = state?.target ?? 12, + ready = answered >= target; + return ( +
+ + Workspace + +

PREFERENCES · WHAT A JOB IS WORTH TO YOU

+

Choose between two jobs. Not between two sliders.

+

+ Nobody knows how much pay they would trade for remote until they are + looking at two real jobs. So the value model is fitted from choices you + make here, and it is what decides which roles reach your plan. +

+ {message && ( +
+ {message} +
+ )} +
+
+ Comparisons made + + {answered.toString().padStart(2, '0')} + /{target} + + + {ready ? 'Enough to rank your pool' : 'A few more sharpens it'} + +
+
+ Postings to draw from + {(state?.pool ?? 0).toString().padStart(2, '0')} + Held in your workspace +
+
+ Weekly attention + {minutes} + Minutes the plan is sized to +
+
+ + Revealed, not declared. + Each answer is one constraint on the weights. +
+
+ + {state?.pair ? ( +
+

Which of these would you rather have?

+

+ Assume you would get either one. Pick the job you would actually + take — there is no wrong answer, only your answer. +

+
+ + post( + { + action: 'choose', + winner: state.pair!.a.job_key, + loser: state.pair!.b.job_key, + }, + 'Recorded. The value model refits after every answer.', + ) + } + /> + or + + post( + { + action: 'choose', + winner: state.pair!.b.job_key, + loser: state.pair!.a.job_key, + }, + 'Recorded. The value model refits after every answer.', + ) + } + /> +
+
+ ) : ( +
+

No comparison to offer

+

+ {(state?.pool ?? 0) < 2 + ? 'Import or pull some postings first — comparisons are made over real jobs, not invented ones.' + : 'Every informative pair in the current pool has been asked. Pull more postings to keep refining.'} +

+
+ )} + +
+

What the choices imply

+

+ Weights are shares of one whole, so they read as relative pull. A + negative weight means you have been trading that attribute away. +

+ {answered === 0 && ( +

+ No opinion yet. Relay will not invent one — until you answer, every + posting scores the same. +

+ )} + {answered > 0 && + state && + Object.entries(state.weights).map(([name, value]) => ( +
+ {name} +
+
+
+ + {value >= 0 ? '+' : ''} + {value.toFixed(2)} + +
+ ))} + {answered > 0 && ( +
+ +
+ )} +
+ +
+

+ Weekly attention budget +

+

+ One number, and the whole plan is sized against it. As review + calibrates the writer, the same minutes buy more applications. +

+
+ setMinutes(Number(e.target.value))} + /> + +
+
+
+ Relay / SyberLabsPreferences decide what reaches your week. +
+
+ ); +} diff --git a/app/profile/page.tsx b/app/profile/page.tsx new file mode 100644 index 0000000..dbf35d2 --- /dev/null +++ b/app/profile/page.tsx @@ -0,0 +1,380 @@ +'use client'; +import { useCallback, useEffect, useState } from 'react'; +import Link from 'next/link'; +import { + ArrowLeft, + BadgeCheck, + CircleAlert, + FileText, + Plus, + Trash2, +} from 'lucide-react'; +type Fact = { + id: string; + claim: string; + evidence: string; + tag: string; + status: string; + verified: string | null; + expires: string | null; +}; +type Rule = { id: string; rule: string; scope: string }; +type Candidate = { claim: string; evidence: string; tag: string }; +export default function Profile() { + const [facts, setFacts] = useState([]), + [rules, setRules] = useState([]), + [version, setVersion] = useState(1), + [usable, setUsable] = useState(0), + [resume, setResume] = useState(''), + [candidates, setCandidates] = useState([]), + [chosen, setChosen] = useState>(new Set()), + [expiry, setExpiry] = useState>({}), + [rule, setRule] = useState(''), + [scope, setScope] = useState('global'), + [busy, setBusy] = useState(false), + [message, setMessage] = useState(''), + [signedOut, setSignedOut] = useState(false); + const refresh = useCallback(async () => { + const r = await fetch('/api/profile'); + const data = (await r.json()) as { + facts: Fact[]; + rules: Rule[]; + version: number; + usable: number; + error?: string; + }; + if (r.status === 401) { + setFacts([]); + setRules([]); + setCandidates([]); + setResume(''); + setSignedOut(true); + return; + } + if (!r.ok) throw Error(data.error); + setFacts(data.facts); + setRules(data.rules); + setVersion(data.version); + setUsable(data.usable); + }, []); + useEffect(() => { + void Promise.resolve() + .then(() => refresh()) + .catch((e: Error) => setMessage(e.message)); + }, [refresh]); + async function run(body: Record, note: string) { + setBusy(true); + setMessage(''); + try { + const r = await fetch('/api/profile', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const data = (await r.json()) as { error?: string }; + if (!r.ok) throw Error(data.error); + await refresh(); + setMessage(note); + return data; + } catch (e) { + setMessage( + e instanceof Error ? e.message : 'Unable to complete request.', + ); + } finally { + setBusy(false); + } + } + async function extract() { + setBusy(true); + setMessage(''); + try { + const r = await fetch('/api/profile', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action: 'extract', text: resume }), + }); + const data = (await r.json()) as { + candidates?: Candidate[]; + error?: string; + }; + if (!r.ok) throw Error(data.error); + setCandidates(data.candidates!); + setChosen(new Set(data.candidates!.map((_, i) => i))); + setMessage( + `${data.candidates!.length} candidate facts found. Nothing is saved until you add them, and nothing is usable until you verify it.`, + ); + } catch (e) { + setMessage(e instanceof Error ? e.message : 'Unable to read resume.'); + } finally { + setBusy(false); + } + } + const proposed = facts.filter((f) => f.status === 'Proposed'), + verified = facts.filter((f) => f.status === 'Verified'); + if (signedOut) + return ( +
+

Your profile

+

Sign in to load your fact ledger and style card.

+ {/* oxlint-disable-next-line next/no-html-link-for-pages -- Sites authentication requires top-level navigation. */} + + Sign in with ChatGPT + +
+ ); + return ( +
+ + Workspace + +

PROFILE · WHAT THE AGENT WRITES FROM

+

Facts it may claim. Voice it must use.

+

+ The fact ledger is checked: a draft may only make a claim traceable to a + verified fact here. The style card is learned from your corrections + during review. +

+
+
+ Verified and usable + {usable.toString().padStart(2, '0')} + Citable by the writing agent +
+
+ Awaiting your check + {proposed.length.toString().padStart(2, '0')} + Extracted, not yet usable +
+
+ Style rules + {rules.length.toString().padStart(2, '0')} + Learned from review +
+
+ Profile version + {version.toString().padStart(2, '0')} + Stamped on every draft +
+
+ {message && ( +
+ {message} +
+ )} +
+

+ Seed the ledger from a resume +

+

+ Extraction runs locally and proposes candidate lines only. It never + marks anything verified. +

+