From 9e307b92447aeff6fdce98bc696d9bb20181fe06 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 6 Sep 2026 00:40:18 +0000 Subject: [PATCH 1/3] Land open PRs and remaining in-repo issue fixes onto current main Replay unique trees from ChatGPT/Codex public-copy (#13), tracker CSV plus session expiry (#11/#15), local-dev Node/port/sign-in with a Windows-safe Node guard (#12/#19), copy/paste draft handoffs (#24), and the profile calibration loop (#26). Bump shadcn to 4.20.1 (#32). Keep selected-job review history retrievable beyond the global 200-event window, allow assistant packets for valid jobs without a posting URL, and make compiled production failures dump status, body, and process output without retrying saves. Closes #7 Closes #8 Closes #9 Closes #17 Closes #19 Closes #22 Co-authored-by: sykosyber --- .github/pull_request_template.md | 2 + .github/workflows/ci.yml | 1 + .node-version | 1 + .nvmrc | 1 + README.md | 112 ++++++- app/about/page.tsx | 12 +- app/agent-tools.ts | 218 ++++++++------ app/api/drafts/route.ts | 245 ++++++++++++++++ app/api/profile/route.ts | 143 +++++++++ app/api/workspace/route.ts | 38 ++- app/connections.tsx | 155 +++++++--- app/globals.css | 159 ++++++++++ app/profile/page.tsx | 373 ++++++++++++++++++++++++ app/review/page.tsx | 399 +++++++++++++++++++++++++ app/tracker-import.tsx | 233 +++++++++++++++ app/workspace.tsx | 257 ++++++++++++---- db/schema.ts | 55 ++++ docs/OPENAI-RELEASE.md | 11 + docs/PUBLIC-COPY.md | 36 +++ docs/public-copy.json | 54 ++++ drizzle/0003_profile_calibration.sql | 54 ++++ drizzle/meta/_journal.json | 9 +- integrations/GROK_BOT.md | 25 ++ integrations/OBSIDIAN.md | 2 +- integrations/OPENAI.md | 49 ++++ integrations/README.md | 29 +- integrations/codex.mjs | 69 +++++ integrations/connectors.mjs | 7 +- integrations/relay.mjs | 35 ++- lib/assistant-handoff.ts | 74 +++++ lib/domain.ts | 13 + lib/editor.ts | 54 +++- lib/integration-files.ts | 98 ++++++- lib/profile.ts | 405 ++++++++++++++++++++++++++ lib/resume.ts | 69 +++++ lib/store.ts | 40 +++ lib/tracker-csv.ts | 113 +++++++ lib/workspace-events.ts | 35 +++ lib/workspace-refresh.ts | 192 ++++++++++++ package.json | 14 +- pnpm-lock.yaml | 8 + pnpm-workspace.yaml | 1 + scripts/ci/production-diagnostics.mjs | 25 ++ scripts/ci/run-integration.mjs | 6 +- scripts/ci/run-production.mjs | 68 ++++- scripts/ci/run-unit.mjs | 7 +- scripts/ensure-node.mjs | 10 + scripts/sync-public-copy.mjs | 142 +++++++++ tests/api.test.mjs | 150 +++++++++- tests/assistant.test.mjs | 164 +++++++++++ tests/auth.test.mjs | 12 +- tests/calibration.test.mjs | 188 ++++++++++++ tests/connectors.test.mjs | 10 +- tests/deployment.test.mjs | 6 +- tests/domain.test.mjs | 20 +- tests/e2e/assistant.spec.ts | 107 +++++++ tests/e2e/tracker-expiry.spec.ts | 61 ++++ tests/e2e/workspace.spec.ts | 137 ++++++++- tests/editor.test.mjs | 150 +++++++++- tests/fixtures/tracker-example.csv | 3 + tests/import.test.mjs | 64 +++- tests/obsidian.test.mjs | 244 +++++++++++++++- tests/packet-identity.test.mjs | 124 ++++++++ tests/production-diagnostics.test.mjs | 31 ++ tests/profile.test.mjs | 352 ++++++++++++++++++++++ tests/public-copy.test.mjs | 60 ++++ tests/tracker-csv.test.mjs | 129 ++++++++ tests/workspace-events.test.mjs | 44 +++ tests/workspace-refresh.test.mjs | 276 ++++++++++++++++++ vite.config.ts | 49 +++- 70 files changed, 6231 insertions(+), 308 deletions(-) create mode 100644 .node-version create mode 100644 .nvmrc create mode 100644 app/api/drafts/route.ts create mode 100644 app/api/profile/route.ts create mode 100644 app/profile/page.tsx create mode 100644 app/review/page.tsx create mode 100644 app/tracker-import.tsx create mode 100644 docs/OPENAI-RELEASE.md create mode 100644 docs/PUBLIC-COPY.md create mode 100644 docs/public-copy.json create mode 100644 drizzle/0003_profile_calibration.sql create mode 100644 integrations/OPENAI.md create mode 100644 integrations/codex.mjs create mode 100644 lib/assistant-handoff.ts create mode 100644 lib/profile.ts create mode 100644 lib/resume.ts create mode 100644 lib/store.ts create mode 100644 lib/tracker-csv.ts create mode 100644 lib/workspace-events.ts create mode 100644 lib/workspace-refresh.ts create mode 100644 scripts/ci/production-diagnostics.mjs create mode 100644 scripts/ensure-node.mjs create mode 100644 scripts/sync-public-copy.mjs create mode 100644 tests/assistant.test.mjs create mode 100644 tests/calibration.test.mjs create mode 100644 tests/e2e/assistant.spec.ts create mode 100644 tests/e2e/tracker-expiry.spec.ts create mode 100644 tests/fixtures/tracker-example.csv create mode 100644 tests/packet-identity.test.mjs create mode 100644 tests/production-diagnostics.test.mjs create mode 100644 tests/profile.test.mjs create mode 100644 tests/public-copy.test.mjs create mode 100644 tests/tracker-csv.test.mjs create mode 100644 tests/workspace-events.test.mjs create mode 100644 tests/workspace-refresh.test.mjs diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 409860b..57ce298 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -17,3 +17,5 @@ Who needs this change, what failed before, and what can they do afterward? - [ ] No credentials, personal applications, or private research are included. - [ ] Agent findings are fixed or answered with evidence. - [ ] A maintainer other than the author will approve. + +- [ ] Public capabilities, integration limits and lead-engineer credit match `docs/public-copy.json`; run `pnpm public-copy:check` and follow `docs/PUBLIC-COPY.md` when these change. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 353f283..6a3b862 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,7 @@ jobs: - run: pnpm lint - run: pnpm typecheck - run: pnpm test + - run: pnpm public-copy:check - run: pnpm build - name: Bundle the production gateway with the built application run: node scripts/release/prepare.mjs diff --git a/.node-version b/.node-version new file mode 100644 index 0000000..a45fd52 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +24 diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..a45fd52 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24 diff --git a/README.md b/README.md index 77abf3c..26656d9 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,53 @@ # Relay by SyberLabs + **Your job search should remember what you've done.** -Relay is a job-search review workspace for people working with AI assistants. Bring research from multiple sources into one job history, prepare exact drafts, and keep interview follow-ups alongside the application. +A job-search review workspace that keeps research, application history, and exact accepted drafts together across your tools. + +**Lead engineer: [Seth Carlson](https://github.com/sdcarlson).** ## Available in this early release -- 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. -- Import Notion research through a read-only command connector. -- Use Obsidian for role research, interview notes and follow-up planning; preview selected notes together, return drafts to their original job version, and export job context with source history. -- Prepare drafts through the Claude API using your verified facts and your own credentials. -- Exchange validated research and draft files with Grok Bot in its VM. -- Explore fictional example records. No real applicant data is included. +- Consolidate repeated posting URLs while preserving source history. +- Keep interview notes and follow-ups without resetting application status. +- Accept an exact draft; changing the wording requires review again. +- Import a tracker CSV through explicit column mapping and a record preview. Source statuses remain research; existing Relay status and accepted drafts are preserved. +- Explore fictional example records; no real applicant data is included. + +## Integrations + +- **[ChatGPT](integrations/OPENAI.md)**: Prepared prompts and JSON file handoffs for draft review. +- **[Codex](integrations/OPENAI.md)**: Prepared prompts, validated draft files, or local drafting through the signed-in Codex CLI. +- **[Obsidian](integrations/OBSIDIAN.md)**: Selected research notes, version-bound draft notes, and job context exports. +- **[Notion](integrations/README.md)**: Read-only research import through the local command connector. +- **[Claude](integrations/README.md)**: Draft preparation through the Claude API with your own credentials. +- **[Grok Bot](integrations/GROK_BOT.md)**: Validated research and draft file exchange in the Bot's VM. +- **[Tracker CSV](integrations/README.md)**: Explicit column mapping and preview of a local comma-separated tracker file as research. + +Integrations require explicit setup or file handoffs. Returned drafts require human review. No automatic application sending or background account sync is included. + +ChatGPT uses a prompt/file handoff; Codex also supports a local CLI adapter. This release does not include a hosted ChatGPT app or MCP connection. -[Integration setup](integrations/README.md) | [Grok Bot instructions](integrations/GROK_BOT.md) | [Launch copy](LAUNCH.md) +[Integration setup](integrations/README.md) | [ChatGPT and Codex guide](integrations/OPENAI.md) | [Launch copy](LAUNCH.md) + [Development workflow](CONTRIBUTING.md) | [Delivery and review](docs/delivery.md) | [Team board](https://github.com/orgs/SyberLabs/projects/1) +## Why Relay + +When another assistant rediscovers a role or rewrites a draft, you need to know what came before and whether the new text was actually reviewed. Relay makes those distinctions explicit: + +- **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.** Selected notes and validated files can supply research and drafts. Relay keeps the review record across those handoffs. + +For example: import a role from Notion, prepare a draft with Claude, accept it, and later add an Obsidian research note for the same posting. The note adds context without replacing your draft or approving new wording. A later draft change needs review again. + +This is Relay's product focus, not a claim of exclusive features or a proven advantage. Job tracking, AI writing, interview notes, and human review already exist elsewhere. Relay records acceptance inside its workspace; it does not verify every claim or prove which words were submitted to an employer. URL matching also cannot identify every repost across different job boards. + + ## GrokCell bot templates For model-specific research practices, reusable handoffs, and a proposed evaluation plan, see [Context management for Relay](context-management/README.md). The guide distinguishes documented provider capabilities from Relay's implemented integrations. @@ -27,33 +56,90 @@ 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. Logged drafts accumulate until review is worth your time (`/review`). Staging a graduated cluster's draft is not acceptance: status is untouched and accepting an exact draft remains a human action in the workspace. Relay still does not send applications. + ## Obsidian workflow -Select a job, open **Connect Obsidian, Grok Bot, Notion & Claude**, choose the note purpose and **Create note for selected job**. Edit the downloaded note in your vault, then load it in Relay, review its contents and preview matches before importing. New jobs can start from the downloadable example. Several research notes can be imported together. +Select a job, open **Connect your tools**, choose the note purpose and **Create note for selected job**. Edit the downloaded note in your vault, then load it in Relay, review its contents and preview matches before importing. New jobs can start from the downloadable example. Several research notes can be imported together. Use **Edit draft in Obsidian** for an application or follow-up draft that returns to the same job version for review. **Download job context** includes source history as a reference snapshot. Research preserves existing status and approval; loading a draft never accepts or sends it. This is an explicit file handoff, with no plugin, vault scanning or background synchronization. [Complete Obsidian guide](integrations/OBSIDIAN.md) | [Architecture and data ownership](ARCHITECTURE.md) +## ChatGPT and Codex + +Choose **Prepare for ChatGPT** or **Prepare for Codex** in **Connect your tools**, share the selected prompt, and return the JSON result for review. Codex can also prepare drafts through its signed-in CLI. [Complete setup and boundaries](integrations/OPENAI.md). + +## Keeping public pages current + +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. + ## Run locally Node 24 and pnpm are required. From the repository root: ```sh +# .nvmrc / .node-version are `24` +nvm install && nvm use # or: fnm install && fnm use +# mise use node@24 +# asdf install nodejs 24 && asdf set nodejs 24 + +node scripts/ensure-node.mjs # checks the running Node version; no Bash required +node -v # must be >= 24 pnpm install --frozen-lockfile 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 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`. +`pnpm dev` binds **http://localhost:3000/** (Vite `strictPort`). Use that URL. Miniflare/workerd may also print an internal `127.0.0.1:NNNN` bind — ignore it for the browser and curl. + +`pnpm start` (after `pnpm build`) binds the built Worker at **http://127.0.0.1:8787/**. + +Do not expose either server to the internet. Load fictional examples or import your own records. The product introduction is at `/about`. + +### Local sign-in + +On `pnpm dev`, the Sites Vite plugin mocks ChatGPT sign-in on the Vite URL only: + +- Browser: **Sign in with ChatGPT** → `/signin-with-chatgpt?return_to=/` +- Mock identity: `local_seedy` / `seedy@sites.test` + +`/signin-with-chatgpt` is not a Worker route. `pnpm start` and any workerd-only port return 404 for it. Send Sites identity headers instead (fictional values only): + +```sh +curl -sS http://127.0.0.1:8787/api/workspace \ + -H 'oai-authenticated-user-id: local-dev' \ + -H 'oai-authenticated-user-email: local@example.com' +``` + +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. ## Integration boundaries The connectors are runnable local commands with file import/export in the app. Notion and Claude require your own credentials. A local assisted trial retrieved real Notion records 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. Bot JSON was transcribed by hand into a validated file and loaded in the browser; fully automatic Bot file transfer is not validated. Browser acceptance, reload, and reimport kept the accepted draft, Ready status, two observations (deduplicated), and review history. 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. This validates a local assisted workflow, not independent user adoption or unattended production. +## Where Relay fits with existing tools + +Use your preferred discovery and application tools alongside Relay. [Simplify](https://simplify.jobs/) already offers job matching, autofill, resume tailoring, and tracking. Its [Gmail integration](https://help.simplify.jobs/articles/0236686-email-integration) also includes reviewed AI emails and suggested status changes. Relay's focus is preserving research and exact draft decisions across tool handoffs. + +**First compatibility path: tracker CSV → Relay preview.** Simplify documents [CSV import and export](https://help.simplify.jobs/en/articles/2140179-using-the-job-tracker). In Relay, open **Import a tracker CSV**, choose your file, confirm the company, role and employer posting URL columns, and preview before saving. Optional status and notes columns are preserved as research. Every new job starts Held; source statuses never approve a draft or synchronize the application pipeline. Other columns are explicitly listed as omitted. + +This is a file importer, not a Simplify account connection or partnership. CSV handling is tested with fictional fixtures and a Chromium journey covering column selection, preview, import, acceptance, repeat import and reload; a real Simplify export has not yet been validated. Files need posting URLs, comma-separated columns and at most 200 opportunity rows. See the [CSV setup guide](integrations/README.md#tracker-csv--relay) and [fictional example](tests/fixtures/tracker-example.csv). + +Huntr and Teal export compatibility are further candidates, after the first handoff proves useful. Current working integrations and their verification limits are documented in the [setup guide](integrations/README.md). Market positioning was reviewed against vendor documentation on September 5, 2026; repeat use and willingness to pay remain unvalidated. + ## Checks ```sh @@ -63,7 +149,7 @@ pnpm lint node tests/api.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 0002, apply only 0003 from the setup commands; it only adds the profile, draft and review tables and leaves existing rows untouched. For one still on migration 0001, apply 0002 and then 0003. Migration 0002 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. Browser acceptance, reload, and post-acceptance reimport preserved the exact accepted draft, Ready status, two observations, and history. The assisted trial ran on `3b1efd7`; a read-only reopen after fast-forward still showed the accepted record on `59ec7ac`. diff --git a/app/about/page.tsx b/app/about/page.tsx index 76f0497..3491d06 100644 --- a/app/about/page.tsx +++ b/app/about/page.tsx @@ -41,7 +41,7 @@ export default function About() { Bring your assistant

Import Obsidian or Notion research and exchange draft packets with - Grok Bot or Claude. + ChatGPT, Codex, Grok Bot or Claude.

@@ -52,12 +52,20 @@ export default function About() { application status.

What’s available today

+

+ Bring a tracker CSV into Relay: match the company, role and posting URL + columns, preview the records, then import them as research. Original + statuses remain in the notes; existing Relay status and accepted drafts + are preserved. No tracker account connection is required. +

A working review workspace, duplicate detection, source history, and local command integrations. Obsidian notes can be selected for import, and job snapshots downloaded into your vault. Notion imports are read-only. Claude uses your API credentials. Grok Bot uses a documented - file handoff in its VM. + file handoff in its VM. ChatGPT uses a prepared prompt and JSON file + handoff. Codex supports the same handoff or a local command using your + signed-in Codex CLI. Every returned draft requires review.

Relay does not yet run an autonomous job hunt or send applications. Live 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/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..9d88fca 100644 --- a/app/api/workspace/route.ts +++ b/app/api/workspace/route.ts @@ -11,6 +11,10 @@ import { } from '../../../lib/domain'; import seed from '../../../lib/seed.json'; import { packets } from '../../../lib/packets'; +import { + historyPageSize, + INITIAL_EVENT_LIMIT, +} from '../../../lib/workspace-events'; export const dynamic = 'force-dynamic'; const reply = (data: unknown, status = 200) => Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); @@ -28,9 +32,9 @@ export async function GET() { .all(); const events = await db .prepare( - 'SELECT * FROM events WHERE owner=? ORDER BY created DESC LIMIT 200', + 'SELECT * FROM events WHERE owner=? ORDER BY created DESC LIMIT ?', ) - .bind(user) + .bind(user, INITIAL_EVENT_LIMIT) .all(); return reply({ jobs: jobs.results, @@ -155,6 +159,36 @@ export async function POST(request: Request) { return reply({ error: 'Record changed. Reload before saving.' }, 409); return reply({ ok: true }); } + if (b.action === 'history') { + const job = await db + .prepare('SELECT id FROM jobs WHERE id=? AND owner=?') + .bind(b.id, user) + .first(); + if (!job) return reply({ error: 'Record not found.' }, 404); + const limit = historyPageSize(b.limit); + const before = typeof b.before === 'string' && b.before ? b.before : null; + const rows = before + ? await db + .prepare( + 'SELECT * FROM events WHERE owner=? AND job_id=? AND created < ? ORDER BY created DESC LIMIT ?', + ) + .bind(user, b.id, before, limit) + .all() + : await db + .prepare( + 'SELECT * FROM events WHERE owner=? AND job_id=? ORDER BY created DESC LIMIT ?', + ) + .bind(user, b.id, limit) + .all(); + const events = rows.results; + return reply({ + events, + next: + events.length === limit + ? events[events.length - 1]?.created || null + : null, + }); + } return reply({ error: 'Unknown action.' }, 400); } catch (e) { return reply( diff --git a/app/connections.tsx b/app/connections.tsx index d41eff1..c6e69c7 100644 --- a/app/connections.tsx +++ b/app/connections.tsx @@ -1,6 +1,7 @@ 'use client'; import { useState } from 'react'; import Link from 'next/link'; +import { assistantPrompt, type Assistant } from '../lib/assistant-handoff'; import { type EditorTarget } from '../lib/editor'; import { obsidianNote, @@ -12,6 +13,8 @@ import { import { readIntegrationFiles, draftFromResult, + draftFromPastedJson, + selectedJobPacket, } from '../lib/integration-files'; function downloadFile(content: string, filename: string, type: string) { @@ -36,7 +39,7 @@ export function Connections({ id: string; job_key: string; name: string; - url: string; + url: string | null; version: number; status: string; session?: string; @@ -55,29 +58,71 @@ export function Connections({ }) { const [facts, setFacts] = useState(''); const [note, setNote] = useState(''); + const [pasted, setPasted] = useState(''); const [workflow, setWorkflow] = useState('research'); const [loading, setLoading] = useState(false); - function download() { + function editorTarget() { + return current?.session + ? { + jobId: current.id, + session: current.session, + version: current.version, + draft, + job_key: current.job_key, + } + : undefined; + } + function packetText() { + return current + ? JSON.stringify(selectedJobPacket(current, facts, draft), null, 2) + : ''; + } + async function copy() { if (!current) return; - const packet = { - schema: 'relay.packet.v1', - job: { - id: current.id, - key: current.job_key, - name: current.name, - url: current.url, - version: current.version, - status: current.status, - }, - facts, - draft, - }; - downloadFile( - JSON.stringify(packet, null, 2), - 'relay-packet.json', - 'application/json', - ); + try { + await navigator.clipboard.writeText(packetText()); + setNote( + 'Packet copied. It includes only this job, the visible draft, and the facts you supplied.', + ); + } catch { + setNote('Unable to copy to the clipboard. Download the packet instead.'); + } + } + function loadPastedDraft() { + try { + const started = editorTarget(); + onDraft(draftFromPastedJson(pasted, started), started); + setNote( + 'JSON checked. Review the visible draft before saving; if your selection or draft changed, load it again.', + ); + } catch (error) { + setNote( + error instanceof Error ? error.message : 'Unable to read draft JSON.', + ); + } + } + function download(assistant?: Assistant) { + if (!current) return; + const packet = selectedJobPacket(current, facts, draft); + if (assistant) { + try { + downloadFile( + assistantPrompt(packet, assistant), + `relay-${assistant}-prompt.md`, + 'text/markdown', + ); + setNote( + 'Prompt downloaded. Share it with your chosen assistant, save its JSON response, then load that file here for review. Only this job, the visible draft and supplied facts are included.', + ); + } catch (error) { + setNote( + error instanceof Error ? error.message : 'Unable to prepare handoff.', + ); + } + return; + } + downloadFile(packetText(), 'relay-packet.json', 'application/json'); setNote( 'Packet downloaded. It includes only this job, the visible draft, and the facts you supplied.', ); @@ -85,12 +130,12 @@ export function Connections({ return (

- Connect Obsidian, Grok Bot, Notion & Claude + Connect your tools

- Bring research from Obsidian, Notion or Grok Bot, and review a draft - prepared by Claude. Load Obsidian notes directly; other integrations use - the Relay command tool. Accounts are not connected automatically. + Bring research from Obsidian, Notion or Grok Bot, and review drafts + prepared with ChatGPT, Codex or Claude. Choose which files to share. + Accounts are not connected automatically.

About Relay and integration setup ↗ @@ -203,9 +248,34 @@ export function Connections({ />

- + + +
+

+ For ChatGPT or Codex, enter verified facts, download the prepared + prompt, and share it with that assistant. Save its JSON response as a + .json file and load it here. Codex can also prepare a draft through the + local command tool. Returned wording needs review; loading never accepts + or sends it. +

+