diff --git a/README.md b/README.md index 901a6e8..38ac0d3 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ ChatGPT uses a prompt/file handoff; Codex also supports a local CLI adapter. Thi [Integration setup](integrations/README.md) | [ChatGPT and Codex guide](integrations/OPENAI.md) | [Launch copy](LAUNCH.md) +Tracker CSV imports are also available through explicit column mapping and preview. Source statuses remain research; existing Relay status and accepted drafts are preserved. [Tracker CSV setup](integrations/README.md#tracker-csv--relay). + [Development workflow](CONTRIBUTING.md) | [Delivery and review](docs/delivery.md) | [Team board](https://github.com/orgs/SyberLabs/projects/1) ## GrokCell bot templates @@ -75,6 +77,16 @@ Open the local URL printed by the server. Local sign-in is simulated by the Site 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 diff --git a/app/about/page.tsx b/app/about/page.tsx index 5140153..3491d06 100644 --- a/app/about/page.tsx +++ b/app/about/page.tsx @@ -52,6 +52,12 @@ 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, diff --git a/app/globals.css b/app/globals.css index c53f98f..b0d6125 100644 --- a/app/globals.css +++ b/app/globals.css @@ -704,3 +704,35 @@ footer { max-width: 100%; margin-top: 0.5rem; } + +.tracker-fields { + border: 0; + padding: 0; + min-width: 0; +} +.tracker-columns { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; +} +.tracker-fields input:not([type='file']), +.tracker-fields select { + display: block; + width: 100%; + padding: 10px; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--paper); + color: inherit; + font: inherit; +} +.tracker-preview { + max-height: 440px; + overflow: auto; + margin-bottom: 16px; +} +.tracker-preview p, +.tracker-preview pre { + overflow-wrap: anywhere; + white-space: pre-wrap; +} diff --git a/app/tracker-import.tsx b/app/tracker-import.tsx new file mode 100644 index 0000000..a53ffa7 --- /dev/null +++ b/app/tracker-import.tsx @@ -0,0 +1,233 @@ +'use client'; +import { useRef, useState } from 'react'; +import { + readTrackerCsv, + suggestTrackerMapping, + trackerRows, + type TrackerCsv, + type TrackerMapping, +} from '../lib/tracker-csv'; +import type { SourceRow } from '../lib/domain'; + +const fields = [ + ['company', 'Company'], + ['role', 'Role'], + ['url', 'Employer posting URL'], + ['status', 'Source status (optional)'], + ['notes', 'Research notes (optional)'], +] as const; +type Preview = { rows: SourceRow[]; kinds: string[] }; + +export function TrackerImport({ + onImported, + onUnauthorized, +}: { + onImported: () => Promise; + onUnauthorized: () => void; +}) { + const [csv, setCsv] = useState(null); + const [mapping, setMapping] = useState({ + company: '', + role: '', + url: '', + status: '', + notes: '', + }); + const [source, setSource] = useState('Simplify'); + const [preview, setPreview] = useState(null); + const [message, setMessage] = useState(''); + const [busy, setBusy] = useState(false); + const reading = useRef(0); + + async function submit(action: 'preview' | 'import') { + if (!csv) return; + setBusy(true); + setMessage(''); + try { + const rows = + action === 'import' ? preview?.rows : trackerRows(csv, mapping, source); + if (!rows) throw Error('Preview the selected columns first.'); + if (action === 'preview') setPreview(null); + const response = await fetch('/api/workspace', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action, rows }), + }); + if (response.status === 401) { + onUnauthorized(); + return; + } + const result = (await response.json()) as { + error?: string; + items: { kind: string }[]; + }; + if (!response.ok) + throw Error(result.error || 'Unable to import research.'); + if (action === 'preview') { + setPreview({ + rows, + kinds: result.items.map((item: { kind: string }) => item.kind), + }); + setMessage('Check every record below. Nothing has been saved.'); + } else { + setPreview(null); + setCsv(null); + setMessage( + `Imported ${rows.length} research records. Existing application status and draft approval were preserved.`, + ); + try { + await onImported(); + } catch { + setMessage( + 'Research was imported, but the workspace could not refresh. Reload the page to see it.', + ); + } + } + } catch (error) { + setMessage( + error instanceof Error ? error.message : 'Unable to read the tracker.', + ); + } finally { + setBusy(false); + } + } + + return ( +

+ + Import a tracker CSV + +

+ Bring selected opportunities from a Simplify export or another tracker. + Match its columns, then review the records before saving. New jobs enter + the review queue; existing status and accepted drafts stay in Relay. +

+

+ Source statuses, including offers and rejections, are kept as research + only. This does not synchronize your application pipeline. Choose up to + 200 rows with employer posting URLs; add missing URLs to your file + first. +

+
+ + + {csv && ( + <> +
+ {fields.map(([key, label]) => ( + + ))} +
+

+ Omitted columns:{' '} + {csv.headers + .filter((h) => !Object.values(mapping).includes(h)) + .join(', ') || 'none'} + . Keep your original export for all other data. +

+ + + )} +
+ {message && {message}} + {preview && ( + <> +

Review {preview.rows.length} records

+

+ These are the exact research fields that will be saved. Existing + matches may change before import; Relay rechecks them when saving. +

+
+ {preview.rows.map((row, index) => ( +
+ {row.Name}{' '} + {preview.kinds[index]} +

{row.Job}

+
{row.Notes}
+
+ ))} +
+ + + )} +
+ ); +} diff --git a/app/workspace.tsx b/app/workspace.tsx index 266d7eb..5ea770b 100644 --- a/app/workspace.tsx +++ b/app/workspace.tsx @@ -4,7 +4,7 @@ import { validateRows } from '../lib/domain'; import Link from 'next/link'; import { useRelayTools } from './agent-tools'; import { Connections } from './connections'; - +import { TrackerImport } from './tracker-import'; import { applyLoadedDraft, canSave, @@ -19,6 +19,7 @@ import { createWorkspaceSession, editorForJobs, expiredPrivateWorkspace, + expireSession, mutationIsLive, processMutation, processRefresh, @@ -85,6 +86,7 @@ export default function Workspace() { [previewedImport, setPreviewedImport] = useState(''), [showImport, setShowImport] = useState(false); const sessionRef = useRef(createWorkspaceSession()); + const workspaceEpoch = sessionRef.current.gate.epoch; const applyExpired = useCallback(() => { const next = expiredPrivateWorkspace(); setJobs(next.jobs); @@ -351,7 +353,19 @@ export default function Workspace() { ) : !loaded ? (

Opening your workspace…

) : null} - + {!signedOut && loaded && ( + + mutationIsLive(sessionRef.current.gate, { epoch: workspaceEpoch }) + ? refresh() + : Promise.resolve() + } + onUnauthorized={() => { + expireSession(sessionRef.current); + applyExpired(); + }} + /> + )} {!signedOut && ( 2000000) + throw Error('Choose a CSV smaller than 2 MB.'); + let rows: string[][]; + try { + rows = parse(text, { + bom: true, + skip_empty_lines: true, + max_record_size: 100000, + // Reject overflow rather than silently importing only the first page. + on_record(record: string[], context: { records: number }) { + if (context.records > 201) + throw Error('Choose at most 200 opportunity rows.'); + return record; + }, + }); + } catch (error) { + throw Error( + 'Unable to read CSV: ' + + (error instanceof Error ? error.message : 'check quoting and columns.'), + ); + } + if (rows.length < 2) + throw Error('Include a header and at least one opportunity.'); + const headers = rows[0].map((h) => h.trim()); + if ( + headers.length > 50 || + headers.some((h) => !h || h.length > 200) || + new Set(headers.map((h) => h.toLowerCase())).size !== headers.length + ) + throw Error( + 'Use 1–50 distinct, nonempty column names of at most 200 characters.', + ); + return { headers, records: rows.slice(1) }; +} + +export function suggestTrackerMapping(headers: string[]): TrackerMapping { + function find(names: string[]) { + const matches = headers.filter((h) => names.includes(h.toLowerCase())); + return matches.length === 1 ? matches[0] : ''; + } + return { + company: find(['company', 'company name']), + role: find(['role', 'position title', 'job title']), + url: find(['url', 'job url', 'posting url', 'job link']), + status: find(['status', 'application status']), + notes: find(['notes']), + }; +} + +export function trackerRows( + csv: TrackerCsv, + mapping: TrackerMapping, + source: string, +): SourceRow[] { + const label = source.trim(); + if (!label || label.length > 100 || /[\r\n]/.test(label)) + throw Error('Name the source tracker in 1–100 characters on one line.'); + for (const field of ['company', 'role', 'url'] as const) + if (!mapping[field]) + throw Error('Choose the company, role and posting URL columns.'); + const selected = Object.values(mapping).filter(Boolean); + if ( + selected.some((column) => !csv.headers.includes(column)) || + new Set(selected).size !== selected.length + ) + throw Error('Choose a different existing column for each field.'); + return validateRows( + csv.records.map((record, index) => { + const cell = (field: keyof TrackerMapping) => + mapping[field] ? record[csv.headers.indexOf(mapping[field])] : ''; + const company = cell('company').trim(); + const role = cell('role').trim(); + const url = cell('url').trim(); + try { + if (!company || !role || !url) + throw Error('Company, role and posting URL are required.'); + if (url.length > 4000) + throw Error('Posting URL exceeds 4,000 characters.'); + const key = jobKey(url, ''); + const name = `${company} — ${role}`; + const notes = `Tracker: ${label}\nSource status: ${cell('status') || '(not supplied)'}\nImported as research; source status does not change Relay status.\n\n${cell('notes')}`; + if (name.length > 500 || notes.length > 20000) + throw Error( + 'Keep the combined title within 500 characters and research within 20,000.', + ); + return { + url: `tracker-csv:${encodeURIComponent(label.toLowerCase())}:${key}`, + Name: name, + Job: url, + Status: 'Held', + Notes: notes, + }; + } catch (error) { + throw Error( + `Opportunity row ${index + 1}: ${error instanceof Error ? error.message : 'Invalid record.'} No rows were imported.`, + ); + } + }), + ); +} diff --git a/package.json b/package.json index 5f98dd0..1f6d4be 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "public-copy:check": "node scripts/sync-public-copy.mjs --target project --root . --check" }, "dependencies": { + "csv-parse": "7.0.2", "jose": "6.2.12", "react": "19.2.8", "react-dom": "19.2.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3a0d721..68cee96 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -28,6 +28,9 @@ importers: cmdk: specifier: 1.1.1 version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + csv-parse: + specifier: 7.0.2 + version: 7.0.2 date-fns: specifier: 4.1.0 version: 4.1.0 @@ -2321,6 +2324,9 @@ packages: csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + csv-parse@7.0.2: + resolution: {integrity: sha512-uKZghv9UmPkMVLYy//KZ9HFAIJsl7wkhoEdIL0+rhuSY9pZQlhaeGEDPIe+/w7eh81MOql8Q/9+inAGWG6ZHYA==} + d3-array@3.2.4: resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} engines: {node: '>=12'} @@ -5774,6 +5780,8 @@ snapshots: csstype@3.2.3: {} + csv-parse@7.0.2: {} + d3-array@3.2.4: dependencies: internmap: 2.0.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a672d04..91f4c92 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,3 +1,4 @@ +nodeLinker: hoisted allowBuilds: esbuild: true workerd: true diff --git a/tests/api.test.mjs b/tests/api.test.mjs index 913a285..1671540 100644 --- a/tests/api.test.mjs +++ b/tests/api.test.mjs @@ -6,6 +6,11 @@ import { loadObsidian, } from '../lib/obsidian.ts'; import { draftFromResult } from '../lib/integration-files.ts'; +import { + readTrackerCsv, + suggestTrackerMapping, + trackerRows, +} from '../lib/tracker-csv.ts'; const base = process.env.RELAY_TEST_URL || 'http://localhost:3000'; // Only run against a local development server, which uses mock authentication. @@ -171,6 +176,52 @@ assert.throws( draftFromResult(draftResult, { ...target, version: savedObsidian.version }), /matching job/, ); +// The tracker handoff uses the real route and database, including Ready and active jobs. +const tracker = readTrackerCsv( + 'Company,Role,URL,Status,Notes\nExample,Backend,https://example.com/jobs/backend,Rejected,CSV research\nExample,Software,https://example.com/jobs/software,Offer,CSV interview research', +); +const trackerMapping = suggestTrackerMapping(tracker.headers); +const trackerResearch = trackerRows( + tracker, + trackerMapping, + 'Fictional tracker API check', +); +const reviewed = (await call()).data.jobs.find((j) => j.id === job.id); +result = await call({ + action: 'save', + id: reviewed.id, + version: reviewed.version, + status: 'Ready', + draft: 'Exact CSV review draft', + blocker: '', +}); +assert.equal(result.status, 200); +const beforeTracker = (await call()).data; +result = await call({ action: 'preview', rows: trackerResearch }); +assert.equal(result.status, 200); +assert.equal(result.data.new, 0); +assert.deepEqual((await call()).data, beforeTracker); +for (let repeat = 0; repeat < 2; repeat++) { + result = await call({ action: 'import', rows: trackerResearch }); + assert.equal(result.status, 200, JSON.stringify(result.data)); +} +const afterTracker = (await call()).data; +for (const research of trackerResearch) { + const before = beforeTracker.jobs.find((j) => j.url === research.Job); + const after = afterTracker.jobs.find((j) => j.id === before.id); + assert.equal(after.status, before.status); + assert.equal(after.draft, before.draft); + assert.equal(after.accepted_draft, before.accepted_draft); + assert.equal( + afterTracker.sources.filter( + (s) => s.source_url === research.url && s.notes === research.Notes, + ).length, + 1, + ); +} +console.log( + 'PASS: tracker CSV preview has no writes; repeated imports preserve acceptance, active status and source history.', +); result = await call(undefined, { 'oai-authenticated-user-id': 'spoof', 'oai-authenticated-user-email': 'other@example.com', diff --git a/tests/assistant.test.mjs b/tests/assistant.test.mjs index adbabdd..010c8ad 100644 --- a/tests/assistant.test.mjs +++ b/tests/assistant.test.mjs @@ -29,7 +29,7 @@ const target = { draft: '', }; -test('assistant handoffs include only selected context and preserve review authority', () => { +await test('assistant handoffs include only selected context and preserve review authority', () => { for (const provider of ['chatgpt', 'codex']) { const input = { ...packet, @@ -56,7 +56,7 @@ test('assistant handoffs include only selected context and preserve review autho } }); -test('missing facts, invalid identity, empty and oversized drafts stop the handoff', () => { +await test('missing facts, invalid identity, empty and oversized drafts stop the handoff', () => { assert.throws(() => assistantPrompt({ ...packet, facts: '' }, 'chatgpt')); assert.throws(() => assistantPrompt( @@ -74,7 +74,7 @@ test('missing facts, invalid identity, empty and oversized drafts stop the hando assert.throws(() => assistantResult(packet, 'a'.repeat(20001), 'codex')); }); -test('Codex runs with constrained output and Relay owns identity, not the response', async () => { +await test('Codex runs with constrained output and Relay owns identity, not the response', async () => { let directory; const result = await draftCodex( packet, @@ -105,7 +105,7 @@ test('Codex runs with constrained output and Relay owns identity, not the respon await assert.rejects(access(directory)); }); -test('Codex failure or malformed output leaves no draft and cleans temporary files', async () => { +await test('Codex failure or malformed output leaves no draft and cleans temporary files', async () => { let directory; await assert.rejects( draftCodex(packet, async (_exe, _args, options) => { @@ -125,7 +125,7 @@ test('Codex failure or malformed output leaves no draft and cleans temporary fil ); }); -test('CLI prompt and draft file round trip rejects output overwrite', async () => { +await test('CLI prompt and draft file round trip rejects output overwrite', async () => { const dir = await mkdtemp(join(tmpdir(), 'relay-assistant-test-')); try { const input = join(dir, 'packet.json'), diff --git a/tests/auth.test.mjs b/tests/auth.test.mjs index 1c4bf55..4613c4c 100644 --- a/tests/auth.test.mjs +++ b/tests/auth.test.mjs @@ -17,7 +17,7 @@ function request(jwt, headers = {}) { headers: { ...(jwt ? { 'Cf-Access-Jwt-Assertion': jwt } : {}), ...headers }, }); } -test('valid Access identity replaces all spoofed application identity headers', async () => { +void test('valid Access identity replaces all spoofed application identity headers', async () => { const verified = await authenticatedRequest(request(await token(), { 'oai-authenticated-user-id': 'victim', 'oai-authenticated-user-email': 'victim@example.com', 'oai-authenticated-user-full-name': 'Forged Name', 'oai-other': 'forged', @@ -30,12 +30,12 @@ test('valid Access identity replaces all spoofed application identity headers', assert.equal(verified.headers.get('Cf-Access-Jwt-Assertion'), null); assert.equal(verified.headers.get('CF-Access-Client-Secret'), null); }); -test('rejects missing identity and missing provider configuration', async () => { +void test('rejects missing identity and missing provider configuration', async () => { await assert.rejects(authenticatedRequest(request(), env, publicKey)); await assert.rejects(authenticatedRequest(request(await token()), {}, publicKey)); await assert.rejects(authenticatedRequest(request(await token()), { ...env, ACCESS_ISSUER: 'https://attacker.example' }, publicKey)); }); -test('rejects wrong signature, issuer, audience, expired token, and missing human identity', async () => { +void test('rejects wrong signature, issuer, audience, expired token, and missing human identity', async () => { const other = await generateKeyPair('RS256'); for (const jwt of [await token({}, other.privateKey), await token({ iss: 'https://other.cloudflareaccess.com' }), await token({ aud: 'b'.repeat(64) }), await token({ exp: 1 }), await token({ sub: '' }), @@ -43,20 +43,20 @@ test('rejects wrong signature, issuer, audience, expired token, and missing huma await assert.rejects(authenticatedRequest(request(jwt), env, publicKey)); } }); -test('gateway rejects anonymous asset access before invoking assets or application', async () => { +void test('gateway rejects anonymous asset access before invoking assets or application', async () => { const bindings = { ...env, ASSETS: { fetch() { throw new Error('Must not reach assets'); } } }; const app = { fetch() { throw new Error('Must not reach application'); } }; const response = await handleRequest(new Request('https://relay.example.com/_next/static/app.js'), bindings, {}, app, publicKey); assert.equal(response.status, 401); }); -test('readiness reports unavailable database without leaking its error', async () => { +void test('readiness reports unavailable database without leaking its error', async () => { const bindings = { ...env, DB: { prepare() { throw new Error('private database detail'); } } }; const req = new Request('https://relay.example.com/readyz', { headers: { 'Cf-Access-Jwt-Assertion': await token() } }); const response = await handleRequest(req, bindings, {}, {}, publicKey); assert.equal(response.status, 503); assert.equal(await response.text(), 'Service unavailable'); }); -test('service tokens can prove readiness but cannot access human workspace data', async () => { +void test('service tokens can prove readiness but cannot access human workspace data', async () => { const service = request(await token({ email: undefined, sub: '' })); await authenticatedReadiness(service, env, publicKey); await assert.rejects(authenticatedRequest(service, env, publicKey)); diff --git a/tests/connectors.test.mjs b/tests/connectors.test.mjs index 69a5b0e..e971c79 100644 --- a/tests/connectors.test.mjs +++ b/tests/connectors.test.mjs @@ -25,7 +25,7 @@ const page = { Notes: { rich_text: [{ text: { content: 'Interview scheduled' } }] }, }, }; -test('Notion preserves status and returns continuation instead of silently truncating', async () => { +void test('Notion preserves status and returns continuation instead of silently truncating', async () => { const r = await pullNotion( { token: 'test-token', dataSource: 'a'.repeat(32), cursor: 'prior' }, async (url, options) => { @@ -42,7 +42,7 @@ test('Notion preserves status and returns continuation instead of silently trunc assert.equal(r.rows[0].Status, 'Live loop'); assert.equal(r.cursor, 'next'); }); -test('unknown Notion statuses are rejected', () => { +void test('unknown Notion statuses are rejected', () => { assert.throws(() => notionRow({ ...page, @@ -53,7 +53,7 @@ test('unknown Notion statuses are rejected', () => { }), ); }); -test('Claude output remains a draft tied to its original job and version', async () => { +void test('Claude output remains a draft tied to its original job and version', async () => { const result = await draftClaude( { token: 'test-token', model: 'test-model', packet }, async (url, options) => { @@ -70,7 +70,7 @@ test('Claude output remains a draft tied to its original job and version', async assert.equal(result.reviewRequired, true); assert.deepEqual(result.job, packet.job); }); -test('provider errors and truncated responses never produce drafts', async () => { +void test('provider errors and truncated responses never produce drafts', async () => { await assert.rejects( draftClaude( { token: 't', model: 'm', packet }, @@ -88,7 +88,7 @@ test('provider errors and truncated responses never produce drafts', async () => /did not finish/, ); }); -test('packets require verified facts and matching job identity', () => { +void test('packets require verified facts and matching job identity', () => { assert.throws(() => validatePacket({ ...packet, facts: '' })); assert.throws(() => validatePacket({ ...packet, job: { ...packet.job, key: 'different' } }), diff --git a/tests/deployment.test.mjs b/tests/deployment.test.mjs index cb0a9fe..7098bbd 100644 --- a/tests/deployment.test.mjs +++ b/tests/deployment.test.mjs @@ -6,7 +6,7 @@ import { verifyManifest } from '../scripts/release/artifact.mjs'; const env = { ACCESS_ISSUER: 'https://relay.cloudflareaccess.com', ACCESS_AUD: 'a'.repeat(64), CLOUDFLARE_ACCOUNT_ID: 'b'.repeat(32), D1_DATABASE_ID: '11111111-1111-4111-8111-111111111111', WORKER_NAME: 'relay-staging', RELEASE_SHA: 'c'.repeat(40), DEPLOY_URL: 'https://staging.relay.example' }; -test('production configuration cannot expose static assets before identity verification', () => { +void test('production configuration cannot expose static assets before identity verification', () => { const config = releaseConfig(env, {}); assert.equal(config.workers_dev, false); assert.equal(config.preview_urls, false); @@ -15,14 +15,14 @@ test('production configuration cannot expose static assets before identity verif assert.equal(config.no_bundle, true); assert.equal(config.d1_databases[0].binding, 'DB'); }); -test('configuration refuses absent credentials, placeholder database, invalid names, and non-origin URLs', () => { +void test('configuration refuses absent credentials, placeholder database, invalid names, and non-origin URLs', () => { for (const name of Object.keys(env)) assert.throws(() => releaseConfig({ ...env, [name]: '' }, {})); assert.throws(() => releaseConfig({ ...env, D1_DATABASE_ID: '00000000-0000-4000-8000-000000000000' }, {})); for (const url of ['http://example.com', 'https://example.com/path', 'https://name:pass@example.com', 'https://example.com?x=1']) { assert.throws(() => releaseConfig({ ...env, DEPLOY_URL: url }, {})); } }); -test('artifact verification binds release SHA and every byte, rejecting missing and extra files', () => { +void test('artifact verification binds release SHA and every byte, rejecting missing and extra files', () => { const files = Object.fromEntries(['dist/server/index.js', 'dist/server/wrangler.json', 'dist/gateway/worker.js', 'deploy/worker.mjs', 'deploy/access.mjs', 'deploy/handler.mjs'].map(path => [path, 'd'.repeat(64)])); const manifest = { version: 1, sha: env.RELEASE_SHA, files }; verifyManifest(manifest, env.RELEASE_SHA, files); diff --git a/tests/domain.test.mjs b/tests/domain.test.mjs index edc7115..48f9c2f 100644 --- a/tests/domain.test.mjs +++ b/tests/domain.test.mjs @@ -20,11 +20,11 @@ function row(status, job = 'https://example.com/jobs/a', notes = '') { const rows = JSON.parse( readFileSync(new URL('../lib/seed.json', import.meta.url), 'utf8'), ); -test('fictional research finds repeats and earlier submissions', () => { +void test('fictional research finds repeats and earlier submissions', () => { const r = classify(rows, []); assert.deepEqual([r.new, r.known, r.submitted], [3, 1, 1]); }); -test('interview and submitted drafts can be edited without resetting status', () => { +void test('interview and submitted drafts can be edited without resetting status', () => { for (const status of ['Submitted', 'Live loop']) { assert.doesNotThrow(() => validateEdit( @@ -40,7 +40,7 @@ test('interview and submitted drafts can be edited without resetting status', () ); } }); -test('Greenhouse aliases match; employer identity remains distinct', () => { +void test('Greenhouse aliases match; employer identity remains distinct', () => { assert.equal( jobKey('https://boards.greenhouse.io/a/jobs/123?utm_source=x', ''), jobKey('https://job-boards.greenhouse.io/a/jobs/123/', ''), @@ -50,7 +50,7 @@ test('Greenhouse aliases match; employer identity remains distinct', () => { jobKey('https://boards.greenhouse.io/b/jobs/123', ''), ); }); -test('rejects script URLs and invalid records', () => { +void test('rejects script URLs and invalid records', () => { assert.throws(() => jobKey('javascript:alert(1)', '')); assert.throws(() => validateRows([ @@ -58,19 +58,19 @@ test('rejects script URLs and invalid records', () => { ]), ); }); -test('submitted state cannot become a fresh application', () => +void test('submitted state cannot become a fresh application', () => assert.throws(() => validateEdit( { version: 1, status: 'Submitted' }, { version: 1, status: 'Held', draft: 'x', blocker: '' }, ), )); -test('preview merge reports a later Held row as already submitted', () => { +void test('preview merge reports a later Held row as already submitted', () => { const r = classify([row('Held'), row('Submitted'), row('Held')], []); assert.equal(r.items.at(-1).kind, 'submitted'); assert.deepEqual([r.new, r.known, r.submitted], [1, 1, 1]); }); -test('preview keeps Live loop above Submitted for both import orders', () => { +void test('preview keeps Live loop above Submitted for both import orders', () => { const forward = classify([row('Live loop'), row('Submitted')], []); assert.equal(forward.items[1].kind, 'known'); assert.equal(forward.submitted, 0); @@ -78,12 +78,12 @@ test('preview keeps Live loop above Submitted for both import orders', () => { assert.equal(reverse.items[0].kind, 'new'); assert.equal(reverse.items[1].kind, 'submitted'); }); -test('imported Ready is Held locally and source Ready stays Ready', () => { +void test('imported Ready is Held locally and source Ready stays Ready', () => { assert.equal(importedJobStatus('Ready'), 'Held'); for (const status of ['Held', 'Submitted', 'Skip', 'Live loop']) assert.equal(importedJobStatus(status), status); }); -test('rejects a non-string source timestamp', () => { +void test('rejects a non-string source timestamp', () => { assert.throws(() => validateRows([ { @@ -109,7 +109,7 @@ test('rejects a non-string source timestamp', () => { ]), ); }); -test('acceptance requires exact text, no blocker, and current version', () => { +void test('acceptance requires exact text, no blocker, and current version', () => { for (const patch of [{ draft: '' }, { blocker: 'captcha' }, { version: 0 }]) assert.throws(() => validateEdit( diff --git a/tests/e2e/tracker-expiry.spec.ts b/tests/e2e/tracker-expiry.spec.ts new file mode 100644 index 0000000..b973c35 --- /dev/null +++ b/tests/e2e/tracker-expiry.spec.ts @@ -0,0 +1,61 @@ +import { expect, test } from '@playwright/test'; + +for (const contentType of ['text/plain', 'application/json']) { + test(`tracker ${contentType} 401 clears the private workspace`, async ({ + page, + }) => { + await page.route('**/api/workspace', async (route) => { + if (route.request().method() === 'GET') { + await route.fulfill({ + json: { + jobs: [ + { + id: 'expiry-job', + job_key: 'https://example.com/jobs/expiry', + name: 'Expiry Example — Engineer', + url: 'https://example.com/jobs/expiry', + status: 'Held', + draft: 'Private draft', + blocker: '', + accepted_draft: null, + version: 1, + }, + ], + sources: [], + events: [], + }, + }); + } else { + await route.fulfill({ + status: 401, + contentType, + body: + contentType === 'text/plain' + ? 'Unauthorized' + : JSON.stringify({ error: 'Sign in again.' }), + }); + } + }); + await page.goto('/'); + await expect(page.locator('.job').first()).toBeVisible(); + await page.getByText('Import a tracker CSV', { exact: true }).click(); + await page.getByLabel('Choose tracker CSV').setInputFiles({ + name: 'expiry.csv', + mimeType: 'text/csv', + buffer: Buffer.from( + 'Company,Role,URL\nExpiry Example,Engineer,https://example.com/jobs/expiry\n', + ), + }); + await expect( + page.getByText('Read 1 rows locally.', { exact: false }), + ).toBeVisible(); + await page.getByRole('button', { name: 'Preview tracker records' }).click(); + await expect( + page.getByRole('heading', { name: 'Your private workspace' }), + ).toBeVisible(); + await expect(page.locator('.job')).toHaveCount(0); + await expect( + page.getByText('Import a tracker CSV', { exact: true }), + ).toHaveCount(0); + }); +} diff --git a/tests/e2e/workspace.spec.ts b/tests/e2e/workspace.spec.ts index b261fe8..df5db4c 100644 --- a/tests/e2e/workspace.spec.ts +++ b/tests/e2e/workspace.spec.ts @@ -136,3 +136,110 @@ test('import, acceptance, reload and rediscovery preserve the exact reviewed dra expect((await page.request.get('/api/workspace')).status()).toBe(401); expect(errors).toEqual([]); }); + +test('tracker CSV mapping and repeated imports preserve reviewed wording', async ({ + page, +}) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await page.goto('/signin-with-chatgpt?return_to=/'); + const panel = page.locator('details').filter({ + has: page.getByText('Import a tracker CSV', { exact: true }), + }); + await panel.locator('summary').click(); + const csv = + 'Company,Position,Job URL,Status,Notes,Private extra\n' + + 'CSV Browser Example,Engineer,https://example.com/jobs/csv-browser,Applied,"Research, with a comma",OMITTED_MARKER\n'; + const load = async (text: string) => { + await panel.getByLabel('Choose tracker CSV').setInputFiles({ + name: 'fictional-tracker.csv', + mimeType: 'text/csv', + buffer: Buffer.from(text), + }); + await expect(panel.getByText(/Read 1 rows locally/)).toBeVisible(); + await panel + .getByRole('combobox', { name: 'Role', exact: true }) + .selectOption('Position'); + }; + await load(csv); + await expect(panel.getByText(/Omitted columns: Private extra/)).toBeVisible(); + await expect(panel.getByRole('button', { name: /^Import 1/ })).toHaveCount(0); + await panel.getByRole('button', { name: 'Preview tracker records' }).click(); + await expect( + panel.getByText('Check every record below. Nothing has been saved.'), + ).toBeVisible(); + let workspace = await (await page.request.get('/api/workspace')).json(); + expect( + workspace.jobs.some((job: { job_key: string }) => + job.job_key.endsWith('/csv-browser'), + ), + ).toBe(false); + await expect(panel.getByText(/Source status: Applied/)).toBeVisible(); + await expect(panel.getByText('OMITTED_MARKER')).toHaveCount(0); + + // Even changing the source label requires another preview of the exact rows. + await panel.getByLabel('Source tracker').fill('Fictional tracker'); + await expect(panel.getByRole('button', { name: /^Import 1/ })).toHaveCount(0); + await panel.getByRole('button', { name: 'Preview tracker records' }).click(); + await panel + .getByRole('button', { name: 'Import 1 research records' }) + .click(); + await expect(panel.getByText(/Imported 1 research records/)).toBeVisible(); + workspace = await (await page.request.get('/api/workspace')).json(); + const job = workspace.jobs.find((item: { job_key: string }) => + item.job_key.endsWith('/csv-browser'), + ); + expect(job.status).toBe('Held'); + expect( + workspace.sources.filter( + (item: { job_key: string }) => item.job_key === job.job_key, + ), + ).toHaveLength(1); + + await page + .getByRole('button', { name: /CSV Browser Example — Engineer/ }) + .click(); + const draft = 'My exact reviewed CSV application answer.'; + await page.getByRole('textbox', { name: 'Blocker or missing fact' }).fill(''); + await page + .getByRole('textbox', { name: 'Application answer or outreach draft' }) + .fill(draft); + await page.getByRole('button', { name: 'Accept exact draft' }).click(); + await expect( + page.getByText('Saved. Your review is preserved.'), + ).toBeVisible(); + + await load(csv); + await panel.getByRole('button', { name: 'Preview tracker records' }).click(); + await panel + .getByRole('button', { name: 'Import 1 research records' }) + .click(); + await expect(panel.getByText(/Imported 1 research records/)).toBeVisible(); + workspace = await (await page.request.get('/api/workspace')).json(); + expect( + workspace.jobs.find((item: { id: string }) => item.id === job.id), + ).toMatchObject({ + status: 'Ready', + draft, + accepted_draft: draft, + }); + expect( + workspace.sources.filter( + (item: { job_key: string }) => item.job_key === job.job_key, + ), + ).toHaveLength(1); + expect( + workspace.sources.find( + (item: { job_key: string }) => item.job_key === job.job_key, + ).notes, + ).not.toContain('OMITTED_MARKER'); + await page.reload(); + await page.getByRole('button', { name: /Accepted drafts/ }).click(); + await page + .getByRole('button', { name: /CSV Browser Example — Engineer/ }) + .click(); + await expect( + page.getByRole('textbox', { name: 'Application answer or outreach draft' }), + ).toHaveValue(draft); + expect(errors).toEqual([]); +}); diff --git a/tests/editor.test.mjs b/tests/editor.test.mjs index 36522b2..5c7d468 100644 --- a/tests/editor.test.mjs +++ b/tests/editor.test.mjs @@ -23,7 +23,7 @@ function target(editor) { draft: editor.draft, }; } -test('refresh during editing keeps unsaved text on the loaded version', () => { +void test('refresh during editing keeps unsaved text on the loaded version', () => { let editor = loadEditor(job('A')); editor = { ...editor, draft: 'local edits' }; editor = reconcileEditor(editor, job('A')); @@ -31,7 +31,7 @@ test('refresh during editing keeps unsaved text on the loaded version', () => { assert.equal(editor.conflict, false); assert.equal(editor.version, 1); }); -test('external update while editing requires reload before save', () => { +void test('external update while editing requires reload before save', () => { let editor = loadEditor(job('A')); editor = { ...editor, draft: 'stale buffer' }; const server = job('A', { version: 2, draft: 'agent draft' }); @@ -45,7 +45,7 @@ test('external update while editing requires reload before save', () => { assert.equal(editor.conflict, false); assert.equal(editor.version, 2); }); -test('clean editor adopts a newer refresh', () => { +void test('clean editor adopts a newer refresh', () => { let editor = loadEditor(job('A')); editor = reconcileEditor( editor, @@ -55,7 +55,7 @@ test('clean editor adopts a newer refresh', () => { assert.equal(editor.version, 2); assert.equal(editor.conflict, false); }); -test('stale save ack after A to B to A does not bless the reloaded editor', () => { +void test('stale save ack after A to B to A does not bless the reloaded editor', () => { const old = job('A'); const original = loadEditor(old); const submitted = { ...original, draft: 'intentionally saved' }; @@ -76,7 +76,7 @@ test('stale save ack after A to B to A does not bless the reloaded editor', () = assert.equal(result.conflict, false); assert.notEqual(result.session, submitted.session); }); -test('save acknowledgement ignores a job switched during the request', () => { +void test('save acknowledgement ignores a job switched during the request', () => { const submitted = loadEditor(job('A')); let editor = loadEditor(job('B', { version: 2, draft: 'draft-B' })); editor = acknowledgeSave(editor, submitted); @@ -84,7 +84,7 @@ test('save acknowledgement ignores a job switched during the request', () => { assert.equal(editor.version, 2); assert.equal(editor.draft, 'draft-B'); }); -test('edits made while a save is in flight stay unsaved on that editor session', () => { +void test('edits made while a save is in flight stay unsaved on that editor session', () => { let editor = loadEditor(job('A')); const submitted = { ...editor, draft: 'saved snapshot' }; editor = { ...editor, draft: 'typed during save' }; @@ -95,7 +95,7 @@ test('edits made while a save is in flight stay unsaved on that editor session', assert.notEqual(editor.draft, editor.baseDraft); assert.equal(editor.session, submitted.session); }); -test('delayed save ack cannot bless an editor already on a newer base', () => { +void test('delayed save ack cannot bless an editor already on a newer base', () => { const original = loadEditor(job('A')); const submitted = { ...original, draft: 'intentionally saved' }; let editor = reconcileEditor( @@ -108,7 +108,7 @@ test('delayed save ack cannot bless an editor already on a newer base', () => { assert.equal(editor.baseDraft, 'from server'); assert.notEqual(editor.session, submitted.session); }); -test('rejected stale save refreshes into a conflict that reload can resolve', () => { +void test('rejected stale save refreshes into a conflict that reload can resolve', () => { let editor = loadEditor(job('A')); editor = { ...editor, draft: 'unsaved after 409' }; const server = job('A', { version: 2, draft: 'newer record' }); @@ -123,7 +123,7 @@ test('rejected stale save refreshes into a conflict that reload can resolve', () assert.equal(editor.conflict, false); assert.equal(canSave(editor), true); }); -test('file load rejects a changed session, version, or typed draft', () => { +void test('file load rejects a changed session, version, or typed draft', () => { const started = loadEditor(job('A')); assert.equal(fileLoadApplies(target(started), target(started)), true); assert.equal( @@ -137,7 +137,7 @@ test('file load rejects a changed session, version, or typed draft', () => { const typed = { ...started, draft: 'typed while reading' }; assert.equal(fileLoadApplies(target(started), target(typed)), false); }); -test('queued editor updater still applies a matching file load without a boolean', () => { +void test('queued editor updater still applies a matching file load without a boolean', () => { const editor = loadEditor(job('A')); const started = target(editor); const queue = []; @@ -148,7 +148,7 @@ test('queued editor updater still applies a matching file load without a boolean assert.equal(queue.length, 1); assert.equal(queue[0](editor).draft, 'from file'); }); -test('stale file-load snapshot cannot overwrite a later editor', () => { +void test('stale file-load snapshot cannot overwrite a later editor', () => { const started = loadEditor(job('A')); const laterB = loadEditor(job('B', { draft: 'keep B' })); const skippedB = applyLoadedDraft( diff --git a/tests/fixtures/tracker-example.csv b/tests/fixtures/tracker-example.csv new file mode 100644 index 0000000..b0cb483 --- /dev/null +++ b/tests/fixtures/tracker-example.csv @@ -0,0 +1,3 @@ +Company,Role,Job URL,Status,Notes +Example Company,Platform Engineer,https://example.com/jobs/tracker-platform,Interview,"Confirm the interview format, then review the draft." +Example Company,Backend Engineer,https://example.com/jobs/tracker-backend,Saved,Research the team before applying. diff --git a/tests/import.test.mjs b/tests/import.test.mjs index 0ac5859..d618797 100644 --- a/tests/import.test.mjs +++ b/tests/import.test.mjs @@ -5,6 +5,11 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { DatabaseSync } from 'node:sqlite'; import { obsidianRow, obsidianExample } from '../lib/obsidian.ts'; +import { + readTrackerCsv, + suggestTrackerMapping, + trackerRows, +} from '../lib/tracker-csv.ts'; import { classify, displayName, @@ -16,7 +21,7 @@ import { } from '../lib/domain.ts'; const root = join(dirname(fileURLToPath(import.meta.url)), '..'); -test('Obsidian reimports preserve active jobs and accepted drafts while keeping note revisions', () => { +void test('Obsidian reimports preserve active jobs and accepted drafts while keeping note revisions', () => { const db = open(); try { for (const status of ['Held', 'Ready', 'Submitted', 'Skip', 'Live loop']) { @@ -128,7 +133,46 @@ function observationsOf(db, owner) { ) .all(owner); } -test('import upsert SQL and observation insert are the workspace statements', () => { + +void test('tracker research preserves all local states and acceptance, deduplicates repeats and retains revisions', () => { + const db = open(); + try { + const csv = readTrackerCsv( + 'Company,Role,URL,Status,Notes\nExample,Engineer,https://example.com/job,Offer,First research', + ); + const mapping = suggestTrackerMapping(csv.headers); + const [row] = trackerRows(csv, mapping, 'Simplify'); + for (const status of ['Held', 'Ready', 'Submitted', 'Skip', 'Live loop']) { + const owner = 'tracker-' + status; + importRow(db, owner, row); + assert.equal(jobOf(db, owner, row.Job).status, 'Held'); + db.prepare( + 'UPDATE jobs SET status=?,draft=?,accepted_draft=?,version=4 WHERE owner=?', + ).run( + status, + 'Exact draft', + status === 'Ready' ? 'Exact draft' : null, + owner, + ); + const before = jobOf(db, owner, row.Job); + importRow(db, owner, row); + assert.equal(observationsOf(db, owner).length, 1); + const revised = readTrackerCsv( + 'Company,Role,URL,Status,Notes\nExample,Engineer,https://example.com/job,Rejected,Changed research', + ); + importRow(db, owner, trackerRows(revised, mapping, 'Simplify')[0]); + const after = jobOf(db, owner, row.Job); + assert.equal(after.status, before.status); + assert.equal(after.draft, before.draft); + assert.equal(after.accepted_draft, before.accepted_draft); + assert.equal(after.version, before.version + 2); + assert.equal(observationsOf(db, owner).length, 2); + } + } finally { + db.close(); + } +}); +void test('import upsert SQL and observation insert are the workspace statements', () => { assert.match(routeSrc, /importedJobStatus\(r\.Status\)/); assert.equal(sqlFromRoute('job').startsWith('INSERT INTO jobs'), true); assert.equal( @@ -136,7 +180,7 @@ test('import upsert SQL and observation insert are the workspace statements', () true, ); }); -test('Live loop outranks Submitted in both import orders and keeps drafts', () => { +void test('Live loop outranks Submitted in both import orders and keeps drafts', () => { const owner = 'owner-a'; const job = 'https://example.com/jobs/loop'; for (const order of [ @@ -161,7 +205,7 @@ test('Live loop outranks Submitted in both import orders and keeps drafts', () = assert.equal(row.draft, 'keep this draft'); } }); -test('repeated imports keep Live loop and every source observation', () => { +void test('repeated imports keep Live loop and every source observation', () => { const db = open(); const owner = 'owner-a'; const job = 'https://example.com/jobs/loop'; @@ -176,7 +220,7 @@ test('repeated imports keep Live loop and every source observation', () => { assert.equal(jobOf(db, owner, job).status, 'Live loop'); assert.equal(observationsOf(db, owner).length, 5); }); -test('new Ready import is Held with no accepted draft; observation stays Ready', () => { +void test('new Ready import is Held with no accepted draft; observation stays Ready', () => { const db = open(); const owner = 'owner-a'; const job = 'https://example.com/jobs/ready'; @@ -188,7 +232,7 @@ test('new Ready import is Held with no accepted draft; observation stays Ready', const [obs] = observationsOf(db, owner); assert.equal(obs.status, 'Ready'); }); -test('duplicate Ready import does not replace a local accepted draft', () => { +void test('duplicate Ready import does not replace a local accepted draft', () => { const db = open(); const owner = 'owner-a'; const job = 'https://example.com/jobs/ready'; @@ -203,7 +247,7 @@ test('duplicate Ready import does not replace a local accepted draft', () => { assert.equal(row.draft, 'Exact accepted text'); assert.equal(observationsOf(db, owner).length, 2); }); -test('observation uniqueness includes job identity and keeps prior rows', () => { +void test('observation uniqueness includes job identity and keeps prior rows', () => { const db = new DatabaseSync(':memory:'); const files = readdirSync(drizzle) .filter((f) => f.endsWith('.sql')) @@ -296,7 +340,7 @@ const mergedStatus = { 'Live loop': 'Live loop', }, }; -test('real SQL and preview merge match the 25 existing/incoming status pairs', () => { +void test('real SQL and preview merge match the 25 existing/incoming status pairs', () => { const owner = 'owner-matrix'; for (const existing of statuses) for (const incoming of statuses) { @@ -343,7 +387,7 @@ test('real SQL and preview merge match the 25 existing/incoming status pairs', ( ); } }); -test('migration repairs invalid imported Ready and keeps valid acceptance and observations', () => { +void test('migration repairs invalid imported Ready and keeps valid acceptance and observations', () => { const db = new DatabaseSync(':memory:'); const files = readdirSync(drizzle) .filter((f) => f.endsWith('.sql')) @@ -402,7 +446,7 @@ test('migration repairs invalid imported Ready and keeps valid acceptance and ob assert.equal(row('live').status, 'Live loop'); assert.equal(row('live').version, 2); }); -test('migration keeps API-valid Ready rows whose blockers are JS-trim whitespace', () => { +void test('migration keeps API-valid Ready rows whose blockers are JS-trim whitespace', () => { const db = new DatabaseSync(':memory:'); const files = readdirSync(drizzle) .filter((f) => f.endsWith('.sql')) diff --git a/tests/obsidian.test.mjs b/tests/obsidian.test.mjs index 85aa9ba..b806409 100644 --- a/tests/obsidian.test.mjs +++ b/tests/obsidian.test.mjs @@ -29,7 +29,7 @@ const handoff = { version: 7, }; -test('Obsidian properties and Markdown are preserved without following links', () => { +void test('Obsidian properties and Markdown are preserved without following links', () => { const note = obsidianExample.replace( 'Example Company — Platform Engineer', @@ -45,7 +45,7 @@ test('Obsidian properties and Markdown are preserved without following links', ( assert.deepEqual(row, obsidianRow(note)); }); -test('note status, draft and acceptance properties never become Relay actions', () => { +void test('note status, draft and acceptance properties never become Relay actions', () => { for (const status of ['Ready', 'Submitted', 'Live loop', 'Unknown']) { const note = obsidianExample.replace( 'relay_id:', @@ -58,7 +58,7 @@ test('note status, draft and acceptance properties never become Relay actions', } }); -test('missing identity, invalid URLs and malformed properties reject the note', () => { +void test('missing identity, invalid URLs and malformed properties reject the note', () => { for (const note of [ '# Plain note', obsidianExample.replace( @@ -89,7 +89,7 @@ test('missing identity, invalid URLs and malformed properties reject the note', assert.throws(() => obsidianRow(note)); }); -test('aliases and oversized input are bounded', () => { +void test('aliases and oversized input are bounded', () => { assert.throws( () => obsidianRow( @@ -117,7 +117,7 @@ test('aliases and oversized input are bounded', () => { ); }); -test('context exports source history and literal drafts without becoming importable research', () => { +void test('context exports source history and literal drafts without becoming importable research', () => { const job = { id: 'job-123', name: 'Example: "Role"\nstatus: Ready', @@ -147,7 +147,7 @@ test('context exports source history and literal drafts without becoming importa assert.throws(() => loadObsidian(exported), /reference only/); }); -test('each workflow creates a research note tied to the selected posting', () => { +void test('each workflow creates a research note tied to the selected posting', () => { for (const workflow of Object.keys(obsidianWorkflows)) { const row = obsidianRow( obsidianResearchNote(handoff, workflow, `note-${workflow}`), @@ -159,7 +159,7 @@ test('each workflow creates a research note tied to the selected posting', () => } }); -test('batch import rejects duplicate IDs and any malformed note without returning partial data', () => { +void test('batch import rejects duplicate IDs and any malformed note without returning partial data', () => { const notes = [ { name: 'one.md', text: obsidianExample }, { @@ -190,7 +190,7 @@ test('batch import rejects duplicate IDs and any malformed note without returnin assert.throws(() => obsidianResearchBatch(large), /too large/); }); -test('draft round trip stages exact wording only for its job and version', () => { +void test('draft round trip stages exact wording only for its job and version', () => { const result = loadObsidian( obsidianDraftNote(handoff, 'Edited in Obsidian.'), ); @@ -250,7 +250,7 @@ test('draft round trip stages exact wording only for its job and version', () => ); }); -test('file loading supports Markdown batches, individual drafts and existing JSON handoffs', async () => { +void test('file loading supports Markdown batches, individual drafts and existing JSON handoffs', async () => { const file = (name, text) => ({ name, size: new TextEncoder().encode(text).length, @@ -285,7 +285,7 @@ test('file loading supports Markdown batches, individual drafts and existing JSO ); }); -test('CLI creates a draft note without facts or credentials and converts it back for review', async () => { +void test('CLI creates a draft note without facts or credentials and converts it back for review', async () => { const folder = await mkdtemp(join(tmpdir(), 'relay-obsidian-draft-')); try { const packet = join(folder, 'packet.json'); @@ -330,7 +330,7 @@ test('CLI creates a draft note without facts or credentials and converts it back } }); -test('command reads only the selected note, leaves it intact, and refuses overwrite', async () => { +void test('command reads only the selected note, leaves it intact, and refuses overwrite', async () => { const folder = await mkdtemp(join(tmpdir(), 'relay-obsidian-')); try { const input = join(folder, 'selected.md'); diff --git a/tests/public-copy.test.mjs b/tests/public-copy.test.mjs index dc3e394..b04f980 100644 --- a/tests/public-copy.test.mjs +++ b/tests/public-copy.test.mjs @@ -11,13 +11,13 @@ const copy = JSON.parse( await readFile(new URL('../docs/public-copy.json', import.meta.url), 'utf8'), ); -test('every advertised integration has a checked-in setup guide', async () => { +await test('every advertised integration has a checked-in setup guide', async () => { for (const item of copy.integrations) await access(new URL('../' + item.guide, import.meta.url)); assert.equal(copy.leadEngineer, 'Seth Carlson'); }); -test('sync preserves all content outside its block and is idempotent', () => { +await test('sync preserves all content outside its block and is idempotent', () => { const prefix = '\ufeffCustom introduction\r\n', suffix = '\r\nOther projects stay intact.\r\n'; const original = prefix + start + '\r\nOld content\r\n' + end + suffix; @@ -32,12 +32,12 @@ test('sync preserves all content outside its block and is idempotent', () => { } }); -test('missing or ambiguous markers fail instead of overwriting a page', () => { +await test('missing or ambiguous markers fail instead of overwriting a page', () => { for (const value of ['custom content', start + end + start, end + start]) assert.throws(() => replaceBlock(value, 'new')); }); -test('website product data is escaped before rendering', () => { +await test('website product data is escaped before rendering', () => { const content = render( { ...copy, stage: '' }, 'website', @@ -46,7 +46,7 @@ test('website product data is escaped before rendering', () => { assert.match(content, /<script>/); }); -test('public links reject executable schemes, other hosts and embedded credentials', () => { +await test('public links reject executable schemes, other hosts and embedded credentials', () => { for (const field of ['repository', 'leadProfile']) { for (const value of [ 'javascript:alert(1)', diff --git a/tests/tracker-csv.test.mjs b/tests/tracker-csv.test.mjs new file mode 100644 index 0000000..00800a8 --- /dev/null +++ b/tests/tracker-csv.test.mjs @@ -0,0 +1,129 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + readTrackerCsv, + suggestTrackerMapping, + trackerRows, +} from '../lib/tracker-csv.ts'; + +const header = 'Company,Role,Job URL,Status,Notes'; +const row = + 'Example,Engineer,https://example.com/jobs/engineer,Offer,Follow up'; +function convert(text) { + const csv = readTrackerCsv(text); + return trackerRows(csv, suggestTrackerMapping(csv.headers), 'Simplify'); +} + +void test('quoted CSV keeps commas, line breaks, escaped quotes, BOM and Unicode as text', () => { + const [result] = convert( + '\uFEFF' + + header + + '\r\n"Example, Inc.",Engineer,https://example.com/jobs/engineer,Rejected,"Ask about café\nSaid ""hello"""\r\n', + ); + assert.equal(result.Name, 'Example, Inc. — Engineer'); + assert.match(result.Notes, /Source status: Rejected/); + assert.match(result.Notes, /café\nSaid "hello"/); + assert.equal(result.Status, 'Held'); +}); + +void test('source lifecycle and Ready never confer local state or draft acceptance', () => { + for (const state of [ + 'Ready', + 'Applied', + 'Interview', + 'Offer', + 'Rejected', + 'Withdrawn', + 'Unknown future status', + ]) { + const [result] = convert(header + '\n' + row.replace('Offer', state)); + assert.equal(result.Status, 'Held'); + assert.ok(result.Notes.includes('Source status: ' + state)); + assert.equal(result.draft, undefined); + assert.equal(result.accepted_draft, undefined); + } +}); + +void test('repeat exports and reordered records keep source identity; source changes retain observations', () => { + const first = convert(header + '\n' + row)[0]; + const secondRow = row.replaceAll('engineer', 'designer'); + const reordered = convert(header + '\n' + secondRow + '\n' + row); + assert.deepEqual(reordered[1], first); + const changed = convert( + header + '\n' + row.replace('Follow up', 'New research'), + )[0]; + assert.equal(changed.url, first.url); + assert.notEqual(changed.Notes, first.Notes); + const csv = readTrackerCsv(header + '\n' + row); + assert.notEqual( + trackerRows(csv, suggestTrackerMapping(csv.headers), 'Huntr')[0].url, + first.url, + ); +}); + +void test('malformed, ambiguous, oversized and empty CSVs fail without truncating', () => { + for (const value of [ + '', + header, + 'Company,company\na,b', + header + '\n"unclosed', + header + '\na,b', + 'A,\nx,y', + ]) + assert.throws(() => readTrackerCsv(value)); + assert.throws(() => readTrackerCsv('x'.repeat(2000001)), /2 MB/); + assert.equal( + convert(header + '\n' + Array(200).fill(row).join('\n')).length, + 200, + ); + assert.throws( + () => convert(header + '\n' + Array(201).fill(row).join('\n')), + /200/, + ); + assert.throws( + () => convert(header + '\n' + row.replace('Follow up', 'x'.repeat(20000))), + /20,000/, + ); +}); + +void test('a missing or unsafe URL rejects the whole batch and identifies its row', () => { + for (const url of [ + '', + 'javascript:alert(1)', + 'ftp://example.com', + 'not a URL', + ]) { + const bad = row.replace('https://example.com/jobs/engineer', url); + assert.throws( + () => convert(header + '\n' + row + '\n' + bad), + /Opportunity row 2:/, + ); + } +}); + +void test('mapping requires distinct selected columns and ambiguous headers need a choice', () => { + const csv = readTrackerCsv(header + '\n' + row); + const mapping = suggestTrackerMapping(csv.headers); + assert.throws( + () => trackerRows(csv, { ...mapping, url: '' }, 'Simplify'), + /Choose/, + ); + assert.throws( + () => trackerRows(csv, { ...mapping, role: 'Company' }, 'Simplify'), + /different/, + ); + assert.throws( + () => trackerRows(csv, { ...mapping, notes: 'Absent' }, 'Simplify'), + /existing/, + ); + assert.throws(() => trackerRows(csv, mapping, ''), /Name the source/); + assert.equal( + suggestTrackerMapping(['Company', 'Role', 'URL', 'Job URL']).url, + '', + ); + assert.match( + trackerRows(csv, { ...mapping, status: '', notes: '' }, 'Simplify')[0] + .Notes, + /not supplied/, + ); +});