diff --git a/README.md b/README.md index 9265bc6..1f5f838 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,17 @@ Relay is a job-search review workspace for people working with AI assistants. Br ## Available in this early release +- Drive the whole loop from a local command line, with exit codes an agent can act on. +- Set what a job is worth to you by choosing between real postings, not by filling in sliders. +- Get a weekly plan sized to the minutes you actually have, chosen to maximise the best single offer. +- Pull public Greenhouse and Lever boards into the same job identity as everything else. +- Record what came back, with a receipt required before anything counts as submitted. +- See exactly which claims each live application commits you to defending. +- Keep a verified fact ledger and a learned style card that direct a writing agent. +- Seed the ledger from pasted resume text, then verify each candidate line before it can be cited. +- Let an agent log drafts unattended; a claim not traceable to a verified fact is refused, not queued. +- Review logged drafts in batches, correcting habits once instead of per letter. +- Earn autonomy per role cluster: a proven cluster stages its own drafts, and still never accepts or sends one. - Consolidate repeated posting URLs and preserve research history. - Edit notes and follow-up drafts on submitted jobs and active interviews without resetting their status. - Accept an exact draft; changing it returns it to review. @@ -22,6 +33,22 @@ The [GrokCell folder](grokcell/README.md) includes First Principles, Product Ide This is a pinned copy of the separately maintained, MIT-licensed [GrokCell project](https://github.com/sdcarlson/grokcell). Propose template improvements upstream, then refresh the copy following [its source record](grokcell/UPSTREAM.md). +## 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: @@ -32,14 +59,36 @@ 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 ``` Open the local URL printed by the server. Local sign-in is simulated by the Sites development plugin; do not expose this development server to the internet. Load fictional examples or import your own records. The product introduction is at `/about`. +## 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. + +**The command line** (`integrations/README.md`) is how an agent reaches all of this without a browser. It is local-only, it shares one client with the future MCP server, and it deliberately cannot accept a draft, verify a fact, close a review or submit anything — adding a transport must never add a capability. A refused draft exits 3 and writes nothing, which is kept distinct from a server failure so an agent never retries its way past the citation gate. + +**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 -The connectors are runnable local commands with file import/export in the app. Notion and Claude require your own credentials. Real Notion records were retrieved read-only through the connected Notion tool; that does not validate the standalone Notion command connector. Claude live access has not been tested. Grok Bot uses a documented command/file adapter, not an assumed proprietary API. A draft was exchanged with the installed Bot, transcribed into a validated file, then loaded in the browser; fully automatic Bot file transfer is not validated. There is no automatic background sync, autonomous hunting, application sending, or LinkedIn messaging. Generated claims still require your review. Production deployment has not been validated. +The connectors are runnable local commands with file import/export in the app. Notion and Claude require your own credentials. Real Notion records were retrieved read-only through the connected Notion tool; that does not validate the standalone Notion command connector. Claude live access has not been tested. Grok Bot uses a documented command/file adapter, not an assumed proprietary API. A draft was exchanged with the installed Bot, transcribed into a validated file, then loaded in the browser; fully automatic Bot file transfer is not validated. There is no automatic background sync, autonomous hunting, application sending, or LinkedIn messaging. 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. No component submits an application: there are no write-plane adapters, and a recorded submission is your own report of something you did elsewhere, carrying the receipt to prove it. Citation enforcement checks that a claim traces to a fact you verified, which is not the same as checking that the surrounding wording is true, so generated text still requires your review. Production deployment has not been validated. ## Checks @@ -48,11 +97,14 @@ pnpm test pnpm exec tsc --noEmit pnpm lint node tests/api.test.mjs +node tests/calibration.test.mjs +node tests/orchestration.test.mjs +node tests/cli-live.test.mjs ``` -For an existing local database already on migration 0001, apply only 0002 from the setup commands. It preserves observations and repairs imported Ready records that lack matching accepted text. Imported Ready is research evidence; a new record stays Held until its exact draft is accepted in Relay. +For an existing local database already on migration 0003, apply only 0004; it adds the preference, choice and outcome tables and adds nullable or defaulted posting columns to `jobs`, leaving existing rows untouched. From 0002, apply 0003 then 0004; from 0001, apply 0002 first. It preserves observations and repairs imported Ready records that lack matching accepted text. Imported Ready is research evidence; a new record stays Held until its exact draft is accepted in Relay. -The last command needs a running local server and writes only fictional test records. Domain, import, editor and connector tests cover status preservation, duplicate matching, imported acceptance, observation identity, editor version conflicts, draft review rules, provider errors and pagination. Connector tests mock vendor responses; they do not prove live account access. API checks verify database read-back, stale edits, exact acceptance, status-preserving follow-up edits and authentication rejection. Local browser and WebMCP reads/import checks were exercised. Preview works before the first import. Browser file import, save and reload preserved source history. User acceptance and post-acceptance reimport are pending. +The last command needs a running local server and writes only fictional test records. Domain, import, editor and connector tests cover status preservation, duplicate matching, imported acceptance, observation identity, editor version conflicts, draft review rules, provider errors and pagination. Connector tests mock vendor responses; they do not prove live account access. Profile tests cover claim detection, citation support, resume extraction, review triggers and cluster graduation. Selection tests cover the preference fit, the expected-maximum arithmetic against hand-computed cases, budget-respecting portfolio choice, board normalisation, and the rule that a terminal outcome can never be reopened by import — checked against the real upsert SQL as well as the TypeScript. The three live suites each need a **fresh local database**, because they exercise one signed-in workspace end to end; run them one at a time after re-applying the migrations. API checks verify database read-back, stale edits, exact acceptance, status-preserving follow-up edits and authentication rejection. Calibration checks run the whole loop against a local server: extraction writing nothing, an unverified citation and an unsupported claim both refused without a row being written, a correction proposing rules, a closed session advancing the profile version, a cluster graduating into unattended staging that leaves status and acceptance alone, and a retired fact blocking further citation. Local browser and WebMCP reads/import checks were exercised. Preview works before the first import. Browser file import, save and reload preserved source history. User acceptance and post-acceptance reimport are pending. ## Hosting and privacy diff --git a/app/agent-tools.ts b/app/agent-tools.ts index 3be3801..18ddec1 100644 --- a/app/agent-tools.ts +++ b/app/agent-tools.ts @@ -1,5 +1,34 @@ 'use client'; import { useEffect } from 'react'; +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 +43,121 @@ 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) + ? 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..5605c9d --- /dev/null +++ b/app/api/outcomes/route.ts @@ -0,0 +1,136 @@ +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) => + ['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, + receipt: (job as { receipt?: string | null }).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); + const entry = validateOutcome(job, b); + const status = statusAfter(entry.kind); + const statements = [ + db + .prepare( + 'INSERT INTO outcomes (id,owner,job_id,kind,detail,receipt,occurred,created) VALUES (?,?,?,?,?,?,?,?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + entry.kind, + entry.detail, + entry.receipt, + entry.occurred, + now, + ), + db + .prepare( + 'INSERT INTO events (id,owner,job_id,kind,detail,created) VALUES (?,?,?,?,?,?)', + ) + .bind( + crypto.randomUUID(), + user, + job.id, + `Outcome: ${entry.kind}`, + JSON.stringify({ occurred: entry.occurred, receipt: entry.receipt }), + now, + ), + ]; + // The receipt is stored on the job as well as the outcome, so the workspace + // can show at a glance which submissions are proven and which arrived from + // an import without one. + if (status && status !== job.status) + statements.push( + 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), + ); + else if (entry.receipt) + statements.push( + db + .prepare('UPDATE jobs SET receipt=? WHERE id=? AND owner=?') + .bind(entry.receipt, job.id, user), + ); + await db.batch(statements); + return reply({ ok: true, status: status ?? job.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..20ab96b --- /dev/null +++ b/app/api/preferences/route.ts @@ -0,0 +1,143 @@ +import { getChatGPTUser } from '../../chatgpt-auth'; +import { database } from '../../../lib/database'; +import { usableFact } from '../../../lib/profile'; +import { corpusOf, fitWeights, nextPair, pairKey } 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, + delta: pair.delta, + }, + }); +} +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 ( + !Array.isArray(b.delta) || + b.delta.some((n: unknown) => typeof n !== 'number') + ) + throw Error('A choice needs its comparison vector.'); + const { pool } = await state(db, user); + const keys = new Set(pool.map((p) => p.job_key)); + if (!keys.has(b.winner) || !keys.has(b.loser)) + throw Error('Those postings are no longer in the pool.'); + 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(b.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 8f876e6..f31ccf4 100644 --- a/app/api/workspace/route.ts +++ b/app/api/workspace/route.ts @@ -14,6 +14,17 @@ import { packets } from '../../../lib/packets'; 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); @@ -68,7 +79,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(), @@ -81,6 +92,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 c53f98f..4dbdc59 100644 --- a/app/globals.css +++ b/app/globals.css @@ -704,3 +704,303 @@ footer { max-width: 100%; margin-top: 0.5rem; } + +.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..3e09257 --- /dev/null +++ b/app/plan/page.tsx @@ -0,0 +1,196 @@ +'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) return setSignedOut(true); + 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..43852ed --- /dev/null +++ b/app/preferences/page.tsx @@ -0,0 +1,285 @@ +'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; delta: number[] }; +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) return setSignedOut(true); + 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, + delta: state.pair!.delta, + }, + 'Recorded. The value model refits after every answer.', + ) + } + /> + or + + post( + { + action: 'choose', + winner: state.pair!.b.job_key, + loser: state.pair!.a.job_key, + delta: state.pair!.delta.map((d) => -d), + }, + '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..ba9654c --- /dev/null +++ b/app/profile/page.tsx @@ -0,0 +1,373 @@ +'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) return setSignedOut(true); + 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. +

+