From 1d29015e2313fc04428dcb086d22b58c433dcdf0 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:55:07 -0600 Subject: [PATCH 01/23] Add fill fields to statements and applications --- core/src/statements.test.ts | 34 ++++++++++++++++++++++++++++++++++ core/src/statements.ts | 3 ++- core/src/types.ts | 3 +++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/core/src/statements.test.ts b/core/src/statements.test.ts index e306166..7a52dee 100644 --- a/core/src/statements.test.ts +++ b/core/src/statements.test.ts @@ -76,6 +76,40 @@ describe('putStatementOps', () => { .record; expect('value' in rec).toBe(false); }); + + it('drops source when the owner edits a fill statement', () => { + const fill: Statement = { + id: 's1', + createdAt: '2026-01-01T00:00:00.000Z', + applicationId: 'a1', + answerKey: 'salary_range', + value: { type: 'text', value: 'x' }, + source: 'fill', + question: 'Expected salary?', + }; + const rec = ( + putStatementOps(fill, { type: 'text', value: 'y' })[0] as { + record: Statement; + } + ).record; + expect('source' in rec).toBe(false); + expect(rec.question).toBe('Expected salary?'); + expect(rec.value).toEqual({ type: 'text', value: 'y' }); + }); + + it('keeps question and still clears exception', () => { + const withQuestion: Statement = { + ...base, + question: 'Expected salary?', + }; + const rec = ( + putStatementOps(withQuestion, { type: 'text', value: 'new' })[0] as { + record: Statement; + } + ).record; + expect(rec.question).toBe('Expected salary?'); + expect('exception' in rec).toBe(false); + }); }); describe('deleteStatementOps', () => { diff --git a/core/src/statements.ts b/core/src/statements.ts index d185c9a..5573e38 100644 --- a/core/src/statements.ts +++ b/core/src/statements.ts @@ -44,13 +44,14 @@ export function newStatement( return statement; } -/** Saves the told value and clears any exception mark. */ +/** Saves the told value, clears any exception mark and drops the fill source. */ export function putStatementOps( statement: Statement, value: AnswerValue | undefined, ): WriteOp[] { const record: Statement = { ...statement }; delete record.exception; + delete record.source; if (value === undefined) delete record.value; else record.value = value; return [{ kind: 'put', store: 'statements', record }]; diff --git a/core/src/types.ts b/core/src/types.ts index 40cc69c..37ba88b 100644 --- a/core/src/types.ts +++ b/core/src/types.ts @@ -30,6 +30,7 @@ export interface Application extends BaseRecord { fillOutcome?: FillOutcome; fillNote?: string; projectsShown?: string; + formUrls?: string[]; } export interface StatusEvent extends BaseRecord { applicationId?: Id; @@ -86,6 +87,8 @@ export interface Statement extends BaseRecord { answerKey?: string; value?: AnswerValue; exception?: boolean; + source?: 'fill'; + question?: string; } export interface Contact extends BaseRecord { companyId?: Id; From 392632f5ce649144c32a06859e3a6cf4f5b46a41 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:56:52 -0600 Subject: [PATCH 02/23] Test that export keeps fill fields --- core/src/export.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/core/src/export.test.ts b/core/src/export.test.ts index f83154d..09b279f 100644 --- a/core/src/export.test.ts +++ b/core/src/export.test.ts @@ -149,6 +149,35 @@ describe('parseExport', () => { expect(parsed.file.settings).toEqual(settings); }); + it('round-trips fill statement fields and formUrls', () => { + const app = { + id: 'a1', + createdAt: T, + formUrls: ['https://jobs.example.com/acme/1'], + }; + const statement = { + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no' as const, value: false }, + source: 'fill' as const, + question: 'Will you require sponsorship?', + }; + const snap: Snapshot = { + ...emptySnapshot(), + applications: [app], + statements: [statement], + }; + const parsed = parseExport( + JSON.stringify(buildExport(snap, {}, { now: () => T })), + ); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(parsed.file.data.applications).toEqual([app]); + expect(parsed.file.data.statements).toEqual([statement]); + }); + it('restores an export without the new fields', () => { const result = parseExport(fixtureText); expect(result.ok).toBe(true); From f3d9bf6c3f567eb3537c23cff91664d5bc09b19e Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:59:45 -0600 Subject: [PATCH 03/23] Find and link the application for a form --- core/src/form-link.test.ts | 197 +++++++++++++++++++++++++++++++++++++ core/src/form-link.ts | 121 +++++++++++++++++++++++ 2 files changed, 318 insertions(+) create mode 100644 core/src/form-link.test.ts create mode 100644 core/src/form-link.ts diff --git a/core/src/form-link.test.ts b/core/src/form-link.test.ts new file mode 100644 index 0000000..0a8776a --- /dev/null +++ b/core/src/form-link.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it } from 'vitest'; +import { + MAX_FORM_URLS, + findApplicationsForForm, + formUrlKey, + linkFormOps, +} from './form-link'; +import { emptySnapshot } from './schema'; +import type { Application, Job, Snapshot, StatusEvent } from './types'; +import { canonicalizeUrl } from './url'; + +const AT = 'T12:00:00.000Z'; + +function snap(parts: { + applications?: Application[]; + jobs?: Job[]; + statusEvents?: StatusEvent[]; +}): Snapshot { + return { ...emptySnapshot(), ...parts }; +} + +function app(id: string, day: string, extra: object = {}): Application { + return { id, createdAt: `2026-01-${day}${AT}`, ...extra }; +} + +const KEY = 'https://example.com/jobs/1'; + +describe('formUrlKey', () => { + it('strips the Lever apply segment', () => { + expect(formUrlKey('https://jobs.lever.co/acme/123/apply')).toBe( + formUrlKey('https://jobs.lever.co/acme/123'), + ); + expect(formUrlKey('https://jobs.eu.lever.co/acme/123/apply/')).toBe( + formUrlKey('https://jobs.eu.lever.co/acme/123'), + ); + }); + + it('strips the Ashby application segment', () => { + expect(formUrlKey('https://jobs.ashbyhq.com/acme/abc/application')).toBe( + formUrlKey('https://jobs.ashbyhq.com/acme/abc'), + ); + }); + + it('otherwise equals canonicalizeUrl', () => { + const url = 'https://job-boards.greenhouse.io/acme/jobs/9?gh_src=x#app'; + expect(formUrlKey(url)).toBe(canonicalizeUrl(url)); + }); + + it('leaves other hosts and other segments alone', () => { + expect(formUrlKey('https://example.com/careers/apply')).toBe( + 'https://example.com/careers/apply', + ); + expect(formUrlKey('https://jobs.lever.co/acme/applyx')).toBe( + 'https://jobs.lever.co/acme/applyx', + ); + }); + + it('is undefined for non-http(s) and unparseable input', () => { + expect(formUrlKey('not a url')).toBeUndefined(); + expect(formUrlKey('javascript:alert(1)')).toBeUndefined(); + expect(formUrlKey('')).toBeUndefined(); + }); +}); + +describe('findApplicationsForForm', () => { + it('matches by formUrls, job canonicalUrl and own url', () => { + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: KEY }], + applications: [ + app('a1', '02', { formUrls: [KEY] }), + app('a2', '03', { jobId: 'j1' }), + app('a3', '04', { url: `${KEY}?utm_source=x` }), + app('a4', '05', { url: 'https://example.com/other' }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['a1', 'a2', 'a3']); + }); + + it('ranks a formUrls match before a newer job match', () => { + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: KEY }], + applications: [ + app('old', '02', { formUrls: [KEY] }), + app('new', '09', { jobId: 'j1' }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['old', 'new']); + }); + + it('orders newest first within a group and does not duplicate', () => { + const data = snap({ + applications: [ + app('a1', '02', { formUrls: [KEY], url: KEY }), + app('a2', '08', { formUrls: [KEY] }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['a2', 'a1']); + }); + + it('excludes archived applications', () => { + const data = snap({ + applications: [app('a1', '02', { formUrls: [KEY] })], + statusEvents: [ + { + id: 'e1', + createdAt: `2026-01-03${AT}`, + applicationId: 'a1', + status: 'rejected', + }, + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual([]); + }); + + it('tolerates odd formUrls', () => { + const data = snap({ + applications: [ + app('a1', '02', { formUrls: 'x' }), + app('a2', '03', { formUrls: [3, null] }), + app('a3', '04', { formUrls: null }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual([]); + expect(findApplicationsForForm(data, 'x')).toEqual([]); + }); +}); + +describe('linkFormOps', () => { + function put(ops: ReturnType, id: string): Application { + const op = ops.find( + (o) => o.kind === 'put' && (o.record as Application).id === id, + ); + return (op as { record: Application }).record; + } + + it('adds the key once', () => { + const data = snap({ applications: [app('a1', '02')] }); + const ops = linkFormOps(data, 'a1', KEY); + expect(ops).toHaveLength(1); + expect(put(ops, 'a1').formUrls).toEqual([KEY]); + }); + + it('returns nothing the second time', () => { + const data = snap({ applications: [app('a1', '02', { formUrls: [KEY] })] }); + expect(linkFormOps(data, 'a1', KEY)).toEqual([]); + }); + + it('moves the key from one application to another', () => { + const data = snap({ + applications: [ + app('a', '02'), + app('b', '03', { formUrls: [KEY], title: 'B' }), + ], + }); + const ops = linkFormOps(data, 'a', KEY); + expect(ops).toHaveLength(2); + expect(put(ops, 'a').formUrls).toEqual([KEY]); + const b = put(ops, 'b'); + expect('formUrls' in b).toBe(false); + expect(b.title).toBe('B'); + }); + + it('keeps the other keys on the application it removes from', () => { + const data = snap({ + applications: [ + app('a', '02'), + app('b', '03', { formUrls: ['https://example.com/x', KEY] }), + ], + }); + expect(put(linkFormOps(data, 'a', KEY), 'b').formUrls).toEqual([ + 'https://example.com/x', + ]); + }); + + it('drops the oldest past the cap and non-strings', () => { + const existing = Array.from( + { length: MAX_FORM_URLS }, + (_, i) => `https://example.com/k${i}`, + ); + const data = snap({ + applications: [app('a', '02', { formUrls: [...existing, 7, null] })], + }); + const urls = put(linkFormOps(data, 'a', KEY), 'a').formUrls; + expect(urls).toHaveLength(MAX_FORM_URLS); + expect(urls?.[0]).toBe('https://example.com/k1'); + expect(urls?.at(-1)).toBe(KEY); + }); + + it('returns nothing for a missing application', () => { + expect(linkFormOps(snap({}), 'nope', KEY)).toEqual([]); + }); + + it('survives a non-array formUrls', () => { + const data = snap({ applications: [app('a', '02', { formUrls: 'x' })] }); + expect(put(linkFormOps(data, 'a', KEY), 'a').formUrls).toEqual([KEY]); + }); +}); diff --git a/core/src/form-link.ts b/core/src/form-link.ts new file mode 100644 index 0000000..d4a29ec --- /dev/null +++ b/core/src/form-link.ts @@ -0,0 +1,121 @@ +import type { WriteOp } from './repository'; +import { currentStatus, isArchived } from './status'; +import type { Application, Id, Snapshot } from './types'; +import { canonicalizeUrl } from './url'; + +// core/ declares no URL global (lib ES2023, types []), so declare the subset used here. +interface UrlLike { + protocol: string; + hostname: string; +} +declare const URL: { new (url: string, base?: string): UrlLike }; + +export const MAX_FORM_URLS = 20; + +// Hosts whose application form lives one path segment below the posting. +const TRAILING_SEGMENTS: Readonly> = { + 'jobs.lever.co': 'apply', + 'jobs.eu.lever.co': 'apply', + 'jobs.ashbyhq.com': 'application', +}; + +/** The key a form is stored and matched under, or undefined for a non-http(s) address. Never throws. */ +export function formUrlKey( + url: string, + relCanonical?: string, +): string | undefined { + try { + const parsed = new URL(url.trim()); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return undefined; + } + const canonical = canonicalizeUrl(url, relCanonical); + const canonicalUrl = new URL(canonical); + const segment = TRAILING_SEGMENTS[canonicalUrl.hostname.toLowerCase()]; + if (segment === undefined) return canonical; + const queryIndex = canonical.indexOf('?'); + const base = queryIndex >= 0 ? canonical.slice(0, queryIndex) : canonical; + const query = queryIndex >= 0 ? canonical.slice(queryIndex) : ''; + const trimmed = base.replace(/\/+$/, ''); + const suffix = `/${segment}`; + if (!trimmed.endsWith(suffix)) return canonical; + return trimmed.slice(0, -suffix.length) + query; + } catch { + return undefined; + } +} + +function formUrlsOf(app: Application): string[] { + const raw: unknown = app.formUrls; + return Array.isArray(raw) + ? raw.filter((v): v is string => typeof v === 'string') + : []; +} + +function newestFirst(a: Application, b: Application): number { + const x = typeof a.createdAt === 'string' ? a.createdAt : ''; + const y = typeof b.createdAt === 'string' ? b.createdAt : ''; + return x < y ? 1 : x > y ? -1 : 0; +} + +/** Active applications a form may belong to, best first: saved form addresses, then job link, then own URL. */ +export function findApplicationsForForm(data: Snapshot, key: string): Id[] { + const jobUrls = new Map(); + for (const job of data.jobs) { + if (typeof job.canonicalUrl === 'string') + jobUrls.set(job.id, job.canonicalUrl); + } + const active = data.applications + .filter((a) => !isArchived(currentStatus(data.statusEvents, a.id))) + .sort(newestFirst); + + const byForm = active.filter((a) => formUrlsOf(a).includes(key)); + const byJob = active.filter( + (a) => typeof a.jobId === 'string' && jobUrls.get(a.jobId) === key, + ); + const byUrl = active.filter( + (a) => typeof a.url === 'string' && formUrlKey(a.url) === key, + ); + + const seen = new Set(); + const result: Id[] = []; + for (const a of [...byForm, ...byJob, ...byUrl]) { + if (seen.has(a.id)) continue; + seen.add(a.id); + result.push(a.id); + } + return result; +} + +/** Links a form to an application, moving the key off any other application that held it. */ +export function linkFormOps( + data: Snapshot, + applicationId: Id, + key: string, +): WriteOp[] { + const target = data.applications.find((a) => a.id === applicationId); + if (!target) return []; + const ops: WriteOp[] = []; + + const held = formUrlsOf(target); + if (!held.includes(key)) { + const next = [...held, key].slice(-MAX_FORM_URLS); + ops.push({ + kind: 'put', + store: 'applications', + record: { ...target, formUrls: next }, + }); + } + + for (const other of data.applications) { + if (other.id === applicationId) continue; + const urls = formUrlsOf(other); + if (!urls.includes(key)) continue; + const record: Application = { ...other }; + const rest = urls.filter((u) => u !== key); + if (rest.length > 0) record.formUrls = rest; + else delete record.formUrls; + ops.push({ kind: 'put', store: 'applications', record }); + } + return ops; +} From a99ed66d84ec49036044beb8cd1ff9c5f7045429 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:03:08 -0600 Subject: [PATCH 04/23] Build what-I-told-them statements from a fill --- core/src/fill-records.test.ts | 292 ++++++++++++++++++++++++++++++++++ core/src/fill-records.ts | 100 ++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 core/src/fill-records.test.ts create mode 100644 core/src/fill-records.ts diff --git a/core/src/fill-records.test.ts b/core/src/fill-records.test.ts new file mode 100644 index 0000000..89ee994 --- /dev/null +++ b/core/src/fill-records.test.ts @@ -0,0 +1,292 @@ +import { describe, expect, it } from 'vitest'; +import { fillRecordOps, MAX_QUESTION, sameAnswerValue } from './fill-records'; +import type { FillResult, FillResultRow } from './fill/result'; +import { emptySnapshot } from './schema'; +import type { Application, Snapshot, Statement } from './types'; + +const T = '2026-01-01T00:00:00.000Z'; + +function makeDeps() { + let n = 0; + return { now: () => T, newId: () => `n${(n += 1)}` }; +} + +function makeData(app: Partial = {}): Snapshot { + const data = emptySnapshot(); + data.applications.push({ id: 'a1', createdAt: T, ...app }); + return data; +} + +function result( + rows: FillResultRow[], + siteType: FillResult['siteType'] = 'other', +): FillResult { + return { url: 'https://example.com/apply', siteType, at: T, rows }; +} + +const yes = { type: 'yes_no', value: true } as const; +const range = { type: 'money_range', min: 100, max: 200 } as const; + +function baseRows(): FillResultRow[] { + return [ + { + label: 'Email', + target: { kind: 'profile', key: 'email' }, + status: 'will_fill', + outcome: 'written', + answerValue: { type: 'text', value: 'a@example.com' }, + }, + { + label: 'Need sponsorship?', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: yes, + }, + { + label: 'Salary range', + target: { kind: 'answer', key: 'salary_range' }, + status: 'matches', + answerValue: range, + }, + { + label: 'Relocate?', + target: { kind: 'answer', key: 'relocation' }, + status: 'differs', + answerValue: yes, + }, + { + label: 'Start date', + target: { kind: 'answer', key: 'earliest_start_date' }, + status: 'will_fill', + outcome: 'not_empty', + answerValue: { type: 'date', value: '2026-02-01' }, + }, + { + label: 'Reason for leaving', + target: { kind: 'answer', key: 'reason_for_leaving' }, + status: 'will_fill', + outcome: 'gone', + answerValue: { type: 'text', value: 'x' }, + }, + { + label: 'Work authorization', + target: { kind: 'answer', key: 'work_authorization' }, + status: 'will_fill', + outcome: 'failed', + answerValue: yes, + }, + { + label: 'X', + target: { kind: 'answer', key: 'x' }, + status: 'not_filled', + answerValue: yes, + }, + ] as FillResultRow[]; +} + +function puts(ops: ReturnType['ops']): Statement[] { + return ops + .filter((o) => o.kind === 'put' && o.store === 'statements') + .map((o) => (o as { record: Statement }).record); +} + +describe('fillRecordOps', () => { + it('records written and matching answer rows only', () => { + const r = fillRecordOps(makeData(), result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(2); + expect(r.alreadyOnForm).toBe(1); + expect(r.missing).toBe(false); + const st = puts(r.ops); + expect(st.map((s) => s.answerKey)).toEqual(['sponsorship', 'salary_range']); + expect(st[0]).toMatchObject({ + id: 'n1', + createdAt: T, + applicationId: 'a1', + value: yes, + source: 'fill', + question: 'Need sponsorship?', + }); + expect(st[1]?.question).toBe('Salary range'); + }); + + it('skips a value already recorded', () => { + const data = makeData(); + data.statements.push({ + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no', value: true }, + }); + const r = fillRecordOps(data, result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(puts(r.ops).map((s) => s.answerKey)).toEqual(['salary_range']); + }); + + it('adds a different value for the same key', () => { + const data = makeData(); + data.statements.push({ + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no', value: false }, + }); + const r = fillRecordOps(data, result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(2); + }); + + it('records one statement for two rows with the same key and value', () => { + const rows: FillResultRow[] = [ + { + label: 'First', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: yes, + }, + { + label: 'Second', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'matches', + answerValue: { ...yes }, + }, + ]; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(r.alreadyOnForm).toBe(0); + expect(puts(r.ops)[0]?.question).toBe('First'); + }); + + it('trims the question and cuts it at 300 characters', () => { + const rows = baseRows().slice(1, 2); + rows[0] = { ...rows[0]!, label: ` ${'q'.repeat(400)} ` }; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(puts(r.ops)[0]?.question).toBe('q'.repeat(MAX_QUESTION)); + expect(MAX_QUESTION).toBe(300); + }); + + it('omits a blank question', () => { + const rows = baseRows().slice(1, 2); + rows[0] = { ...rows[0]!, label: ' ' }; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(puts(r.ops)[0]).not.toHaveProperty('question'); + }); + + it('sets site type only when empty and not other', () => { + const set = fillRecordOps( + makeData(), + result([], 'lever'), + 'a1', + makeDeps(), + ); + expect(set.ops).toHaveLength(1); + expect(set.ops[0]).toMatchObject({ + kind: 'put', + store: 'applications', + record: { id: 'a1', siteType: 'lever' }, + }); + const kept = fillRecordOps( + makeData({ siteType: 'greenhouse' }), + result([], 'lever'), + 'a1', + makeDeps(), + ); + expect(kept.ops).toEqual([]); + const other = fillRecordOps( + makeData(), + result([], 'other'), + 'a1', + makeDeps(), + ); + expect(other.ops).toEqual([]); + }); + + it('gives no ops when nothing is told', () => { + const r = fillRecordOps( + makeData(), + result(baseRows().slice(3)), + 'a1', + makeDeps(), + ); + expect(r).toEqual({ + ops: [], + recorded: 0, + alreadyOnForm: 0, + missing: false, + }); + }); + + it('gives missing: true for a missing application', () => { + const r = fillRecordOps(makeData(), result(baseRows()), 'nope', makeDeps()); + expect(r).toEqual({ + ops: [], + recorded: 0, + alreadyOnForm: 0, + missing: true, + }); + }); + + it('tolerates a null statement value and a non-object answerValue', () => { + const data = makeData(); + data.statements.push( + { + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: null, + } as unknown as Statement, + { + id: 's2', + createdAt: T, + applicationId: 'a1', + answerKey: 'salary_range', + value: 'str', + } as unknown as Statement, + ); + const rows = baseRows(); + rows[2] = { ...rows[2]!, answerValue: 'oops' as never }; + const r = fillRecordOps(data, result(rows), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(r.alreadyOnForm).toBe(0); + expect(puts(r.ops).map((s) => s.answerKey)).toEqual(['sponsorship']); + }); +}); + +describe('sameAnswerValue', () => { + it('treats money ranges as equal with both currency missing', () => { + expect( + sameAnswerValue( + { type: 'money_range', min: 1, max: 2 }, + { type: 'money_range', min: 1, max: 2 }, + ), + ).toBe(true); + }); + + it('differs on period', () => { + expect( + sameAnswerValue( + { type: 'money_range', min: 1, period: 'year' }, + { type: 'money_range', min: 1, period: 'hour' }, + ), + ).toBe(false); + }); + + it('is false for different types and for null', () => { + expect( + sameAnswerValue( + { type: 'text', value: 'a' }, + { type: 'choice', value: 'a' }, + ), + ).toBe(false); + expect(sameAnswerValue(null, null)).toBe(false); + expect(sameAnswerValue(yes, null)).toBe(false); + }); + + it('compares the value field for other types', () => { + expect(sameAnswerValue(yes, { type: 'yes_no', value: true })).toBe(true); + expect(sameAnswerValue(yes, { type: 'yes_no', value: false })).toBe(false); + }); +}); diff --git a/core/src/fill-records.ts b/core/src/fill-records.ts new file mode 100644 index 0000000..303cc8f --- /dev/null +++ b/core/src/fill-records.ts @@ -0,0 +1,100 @@ +import { updateApplicationOps } from './application-ops'; +import type { FillResult } from './fill/result'; +import { isSiteType } from './formhand'; +import type { WriteOp } from './repository'; +import { statementsFor } from './statements'; +import type { Deps, Id, Snapshot, Statement } from './types'; + +export const MAX_QUESTION = 300; + +export interface FillRecord { + ops: WriteOp[]; + recorded: number; + alreadyOnForm: number; + missing: boolean; +} + +// Restored records are not field-checked, so a value may be null, a primitive or an array. +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +const MONEY_FIELDS = ['min', 'max', 'currency', 'period'] as const; + +/** Same type and equal fields for that type. Anything that is not a plain object is never equal. */ +export function sameAnswerValue(a: unknown, b: unknown): boolean { + if (!isPlainObject(a) || !isPlainObject(b)) return false; + if (a.type !== b.type) return false; + if (a.type === 'money_range') { + return MONEY_FIELDS.every((field) => a[field] === b[field]); + } + return a.value === b.value; +} + +/** + * The "what I told them" statements a fill implies, plus a site-type update, + * as one op list. Never throws on odd restored data. + */ +export function fillRecordOps( + data: Snapshot, + result: FillResult, + applicationId: Id, + deps: Deps, +): FillRecord { + const app = data.applications.find((a) => a.id === applicationId); + if (app === undefined) { + return { ops: [], recorded: 0, alreadyOnForm: 0, missing: true }; + } + + const told: { key: string; value: unknown }[] = statementsFor( + data, + applicationId, + ).flatMap((s) => + typeof s.answerKey === 'string' + ? [{ key: s.answerKey, value: s.value }] + : [], + ); + + const ops: WriteOp[] = []; + let recorded = 0; + let alreadyOnForm = 0; + + for (const row of result.rows) { + if (row.target?.kind !== 'answer') continue; + const value: unknown = row.answerValue; + if (!isPlainObject(value)) continue; + const written = row.status === 'will_fill' && row.outcome === 'written'; + const matches = row.status === 'matches'; + if (!written && !matches) continue; + + const key = row.target.key; + if (told.some((t) => t.key === key && sameAnswerValue(t.value, value))) { + continue; + } + told.push({ key, value }); + + const statement: Statement = { + id: deps.newId(), + createdAt: deps.now(), + applicationId, + answerKey: key, + value: { ...value } as Statement['value'], + source: 'fill', + }; + const question = + typeof row.label === 'string' + ? row.label.trim().slice(0, MAX_QUESTION) + : ''; + if (question !== '') statement.question = question; + + ops.push({ kind: 'put', store: 'statements', record: statement }); + recorded += 1; + if (matches) alreadyOnForm += 1; + } + + if (!isSiteType(app.siteType) && result.siteType !== 'other') { + ops.push(...updateApplicationOps(app, { siteType: result.siteType })); + } + + return { ops, recorded, alreadyOnForm, missing: false }; +} From a2efcb7e9a96c157d214cc6266a5ff41ad7ec340 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:07:31 -0600 Subject: [PATCH 05/23] Work out the told panel and its writes --- core/src/told-panel.test.ts | 321 ++++++++++++++++++++++++++++++++++++ core/src/told-panel.ts | 99 +++++++++++ 2 files changed, 420 insertions(+) create mode 100644 core/src/told-panel.test.ts create mode 100644 core/src/told-panel.ts diff --git a/core/src/told-panel.test.ts b/core/src/told-panel.test.ts new file mode 100644 index 0000000..8bf3da8 --- /dev/null +++ b/core/src/told-panel.test.ts @@ -0,0 +1,321 @@ +import { describe, expect, it } from 'vitest'; +import { fixedDeps } from '../testing/fixed-deps'; +import { emptySnapshot } from './schema'; +import { markAppliedOps, recordTickedOps, toldPanel } from './told-panel'; +import type { + Application, + AnswerValue, + CanonicalAnswer, + Snapshot, + Statement, + StatusEvent, +} from './types'; + +const T = '2026-01-05T09:00:00.000Z'; +const yes: AnswerValue = { type: 'yes_no', value: true }; +const notice: AnswerValue = { type: 'text', value: '2 weeks' }; + +const app: Application = { id: 'a1', createdAt: T }; + +function answer( + id: string, + key: string | undefined, + value: AnswerValue = yes, +): CanonicalAnswer { + const c: CanonicalAnswer = { id, createdAt: T }; + if (key !== undefined) c.key = key; + c.value = value; + return c; +} + +/** A canonical answer with no value field at all. */ +function valueless(id: string, key: string): CanonicalAnswer { + return { id, createdAt: T, key }; +} + +function statement( + id: string, + answerKey: string | undefined, + applicationId = 'a1', +): Statement { + const s: Statement = { id, createdAt: T, applicationId }; + if (answerKey !== undefined) s.answerKey = answerKey; + return s; +} + +function event( + id: string, + status: StatusEvent['status'], + extra: Partial = {}, +): StatusEvent { + return { + id, + createdAt: T, + applicationId: 'a1', + status, + occurredOn: '2026-01-05', + ...extra, + }; +} + +function snapshot(parts: Partial = {}): Snapshot { + return { ...emptySnapshot(), applications: [app], ...parts }; +} + +describe('toldPanel', () => { + it('lists canonical answers not yet stated on the application, in canonical order', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + answer('c3', 'relocation'), + ], + }); + const panel = toldPanel(data, 'a1'); + expect(panel.unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + 'notice', + 'relocation', + ]); + expect(panel.missing).toBe(false); + }); + + it('excludes keys already stated on this application, by fill or by hand', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + answer('c3', 'relocation'), + ], + statements: [ + { ...statement('s1', 'sponsorship'), source: 'fill', value: yes }, + statement('s2', 'notice'), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'relocation', + ]); + }); + + it('counts a statement as stating its key whatever its value', () => { + const data = snapshot({ + canonicalAnswers: [answer('c1', 'sponsorship')], + statements: [statement('s1', 'sponsorship')], + }); + expect(toldPanel(data, 'a1').unrecorded).toEqual([]); + }); + + it('ignores statements that belong to another application', () => { + const data = snapshot({ + canonicalAnswers: [answer('c1', 'sponsorship')], + statements: [statement('s1', 'sponsorship', 'a2')], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + ]); + }); + + it('skips keyless, empty-key, valueless and malformed-value answers', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', undefined), + answer('c2', ''), + valueless('c3', 'no_value'), + answer('c4', 'null_value', null as unknown as AnswerValue), + answer('c5', 'array_value', [] as unknown as AnswerValue), + answer('c6', 'string_value', 'yes' as unknown as AnswerValue), + answer('c7', 'sponsorship'), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + ]); + }); + + it('keeps only the first canonical answer for a duplicate key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship', yes), + answer('c2', 'sponsorship', { type: 'yes_no', value: false }), + ], + }); + const panel = toldPanel(data, 'a1'); + expect(panel.unrecorded.map((c) => c.id)).toEqual(['c1']); + }); + + it('uses the first valid answer when an earlier duplicate has no usable value', () => { + const data = snapshot({ + canonicalAnswers: [ + valueless('c1', 'sponsorship'), + answer('c2', 'sponsorship', yes), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.id)).toEqual(['c2']); + }); + + it('offers Mark Applied when there are no status events', () => { + expect(toldPanel(snapshot(), 'a1').offerApplied).toBe(true); + }); + + it('offers Mark Applied at interested', () => { + const data = snapshot({ statusEvents: [event('e1', 'interested')] }); + expect(toldPanel(data, 'a1').offerApplied).toBe(true); + }); + + it.each(['applied', 'interview', 'rejected'] as const)( + 'does not offer Mark Applied at %s', + (status) => { + const data = snapshot({ statusEvents: [event('e1', status)] }); + expect(toldPanel(data, 'a1').offerApplied).toBe(false); + }, + ); + + it('offers Mark Applied again once the applied event is voided', () => { + const data = snapshot({ + statusEvents: [ + event('e1', 'interested', { occurredOn: '2026-01-04' }), + event('e2', 'applied', { voidedAt: '2026-01-06T09:00:00.000Z' }), + ], + }); + expect(toldPanel(data, 'a1').offerApplied).toBe(true); + }); + + it('reports a missing application with an empty, unoffered panel', () => { + expect(toldPanel(snapshot(), 'nope')).toEqual({ + unrecorded: [], + offerApplied: false, + missing: true, + }); + }); +}); + +describe('recordTickedOps', () => { + it('puts one hand-ticked statement per ticked unrecorded key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + ], + }); + const result = recordTickedOps( + data, + 'a1', + ['notice', 'sponsorship'], + fixedDeps(), + ); + expect(result.missing).toBe(false); + expect(result.ops).toEqual([ + { + kind: 'put', + store: 'statements', + record: { + id: 'id-1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: yes, + }, + }, + { + kind: 'put', + store: 'statements', + record: { + id: 'id-2', + // fixedDeps advances one second per now() call + createdAt: '2026-01-05T09:00:01.000Z', + applicationId: 'a1', + answerKey: 'notice', + value: notice, + }, + }, + ]); + }); + + it('writes no source or question on hand-ticked statements', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + const { ops } = recordTickedOps(data, 'a1', ['sponsorship'], fixedDeps()); + expect(ops).toHaveLength(1); + const op = ops[0]; + expect(op?.kind === 'put' && op.store === 'statements').toBe(true); + const record = (op as { record: Statement }).record; + expect('source' in record).toBe(false); + expect('question' in record).toBe(false); + }); + + it('ignores a key that is already recorded and an unknown key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + ], + statements: [statement('s1', 'sponsorship')], + }); + const result = recordTickedOps( + data, + 'a1', + ['sponsorship', 'unknown_key', 'notice'], + fixedDeps(), + ); + expect(result.ops).toHaveLength(1); + expect(result.ops[0]).toMatchObject({ + kind: 'put', + store: 'statements', + record: { answerKey: 'notice' }, + }); + }); + + it('gives one statement for a key ticked twice', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + const result = recordTickedOps( + data, + 'a1', + ['sponsorship', 'sponsorship'], + fixedDeps(), + ); + expect(result.ops).toHaveLength(1); + }); + + it('returns no ops and missing when the application does not exist', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + expect(recordTickedOps(data, 'nope', ['sponsorship'], fixedDeps())).toEqual( + { ops: [], missing: true }, + ); + }); +}); + +describe('markAppliedOps', () => { + it('puts an applied event dated today and reports its id', () => { + const result = markAppliedOps(snapshot(), 'a1', '2026-01-21', fixedDeps()); + expect(result).toEqual({ + ops: [ + { + kind: 'put', + store: 'statusEvents', + record: { + id: 'id-1', + createdAt: T, + applicationId: 'a1', + status: 'applied', + occurredOn: '2026-01-21', + }, + }, + ], + eventId: 'id-1', + missing: false, + }); + }); + + it('returns no ops when the application is already applied', () => { + const data = snapshot({ statusEvents: [event('e1', 'applied')] }); + expect(markAppliedOps(data, 'a1', '2026-01-21', fixedDeps())).toEqual({ + ops: [], + missing: false, + }); + }); + + it('returns no ops and missing when the application does not exist', () => { + expect( + markAppliedOps(snapshot(), 'nope', '2026-01-21', fixedDeps()), + ).toEqual({ ops: [], missing: true }); + }); +}); diff --git a/core/src/told-panel.ts b/core/src/told-panel.ts new file mode 100644 index 0000000..dfa389b --- /dev/null +++ b/core/src/told-panel.ts @@ -0,0 +1,99 @@ +import { addStatusEventOps } from './application-ops'; +import type { WriteOp } from './repository'; +import { currentStatus } from './status'; +import { newStatement, statementsFor } from './statements'; +import type { + AnswerValue, + CanonicalAnswer, + Deps, + Id, + LocalDate, + Snapshot, +} from './types'; + +export interface ToldPanel { + unrecorded: CanonicalAnswer[]; + offerApplied: boolean; + missing: boolean; +} + +// Restored records are not field-checked, so a value may be null, a primitive or an array. +function isPlainObject(value: unknown): value is AnswerValue { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function applicationExists(data: Snapshot, applicationId: Id): boolean { + return data.applications.some((a) => a.id === applicationId); +} + +/** + * The canonical answers this application has no statement for yet, first record + * per key, in canonical order. Malformed answers are skipped, never thrown on. + */ +export function toldPanel(data: Snapshot, applicationId: Id): ToldPanel { + if (!applicationExists(data, applicationId)) { + return { unrecorded: [], offerApplied: false, missing: true }; + } + + const stated = new Set( + statementsFor(data, applicationId).map((s) => s.answerKey), + ); + const seen = new Set(); + const unrecorded: CanonicalAnswer[] = []; + for (const answer of data.canonicalAnswers) { + const key: unknown = answer.key; + if (typeof key !== 'string' || key === '') continue; + if (!isPlainObject(answer.value)) continue; + if (stated.has(key) || seen.has(key)) continue; + seen.add(key); + unrecorded.push(answer); + } + + const current = currentStatus(data.statusEvents, applicationId); + const offerApplied = current === undefined || current.status === 'interested'; + return { unrecorded, offerApplied, missing: false }; +} + +/** One hand-ticked statement per ticked key still unrecorded. Other keys are ignored. */ +export function recordTickedOps( + data: Snapshot, + applicationId: Id, + answerKeys: readonly string[], + deps: Deps, +): { ops: WriteOp[]; missing: boolean } { + const panel = toldPanel(data, applicationId); + if (panel.missing) return { ops: [], missing: true }; + + const ticked = new Set(answerKeys); + const ops: WriteOp[] = panel.unrecorded + .filter((answer) => ticked.has(answer.key ?? '')) + .map((answer): WriteOp => ({ + kind: 'put', + store: 'statements', + record: newStatement(answer, applicationId, deps), + })); + return { ops, missing: false }; +} + +/** Marks the application applied on `today`, only when the panel offers it. */ +export function markAppliedOps( + data: Snapshot, + applicationId: Id, + today: LocalDate, + deps: Deps, +): { ops: WriteOp[]; eventId?: Id; missing: boolean } { + const panel = toldPanel(data, applicationId); + if (panel.missing) return { ops: [], missing: true }; + if (!panel.offerApplied) return { ops: [], missing: false }; + + const ops = addStatusEventOps( + applicationId, + { status: 'applied', occurredOn: today }, + deps, + ); + const eventOp = ops.find( + (op): op is Extract => + op.kind === 'put' && op.store === 'statusEvents', + ); + return { ops, eventId: eventOp?.record.id, missing: false }; +} From dad8c83067d4082c41f86ce8830812ba82f618cc Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:10:48 -0600 Subject: [PATCH 06/23] Create an application from a form page in one write --- core/src/form-application.test.ts | 144 ++++++++++++++++++++++++++++++ core/src/form-application.ts | 63 +++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 core/src/form-application.test.ts create mode 100644 core/src/form-application.ts diff --git a/core/src/form-application.test.ts b/core/src/form-application.test.ts new file mode 100644 index 0000000..02bc80a --- /dev/null +++ b/core/src/form-application.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from 'vitest'; +import { newApplicationFromFormOps } from './form-application'; +import { formUrlKey } from './form-link'; +import type { FillResult } from './fill/result'; +import type { WriteOp } from './repository'; +import { emptySnapshot } from './schema'; +import type { Application, Job, Statement, StatusEvent } from './types'; + +const T = '2026-01-01T00:00:00.000Z'; +const URL = 'https://jobs.lever.co/acme/1/apply'; + +function makeDeps() { + let n = 0; + return { now: () => T, newId: () => `n${(n += 1)}` }; +} + +function held(siteType: FillResult['siteType'] = 'other'): FillResult { + return { + url: URL, + siteType, + at: T, + rows: [ + { + label: 'Need sponsorship?', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: { type: 'yes_no', value: true }, + }, + { + label: 'Relocate?', + target: { kind: 'answer', key: 'relocation' }, + status: 'matches', + answerValue: { type: 'yes_no', value: false }, + }, + ], + }; +} + +function stores(ops: WriteOp[], store: string): WriteOp[] { + return ops.filter((o) => o.kind === 'put' && o.store === store); +} + +describe('newApplicationFromFormOps', () => { + it('makes one job and one linked interested application', () => { + const { ops, applicationId, record } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + const jobs = stores(ops, 'jobs'); + const apps = stores(ops, 'applications'); + expect(jobs).toHaveLength(1); + expect(apps).toHaveLength(1); + const job = (jobs[0] as { record: Job }).record; + const app = (apps[0] as { record: Application }).record; + expect(app.jobId).toBe(job.id); + expect(app.id).toBe(applicationId); + const ev = (stores(ops, 'statusEvents')[0] as { record: StatusEvent }) + .record; + expect(ev.applicationId).toBe(app.id); + expect(ev.status).toBe('interested'); + expect(record).toBeUndefined(); + }); + + it('keys the job by the form url key', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL }, + makeDeps(), + ); + const job = (stores(ops, 'jobs')[0] as { record: Job }).record; + expect(job.canonicalUrl).toBe(formUrlKey(URL)); + expect(job.canonicalUrl).toBeDefined(); + }); + + it('orders company, job, application, status event', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + const order = ops.map((o) => (o.kind === 'put' ? o.store : o.kind)); + expect(order).toEqual([ + 'companies', + 'jobs', + 'applications', + 'statusEvents', + ]); + }); + + it('records held statements against the new application', () => { + const { ops, applicationId, record } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + held(), + ); + expect(record?.recorded).toBe(2); + expect(record?.alreadyOnForm).toBe(1); + const statements = stores(ops, 'statements').map( + (o) => (o as { record: Statement }).record, + ); + expect(statements).toHaveLength(2); + expect(statements.every((s) => s.applicationId === applicationId)).toBe( + true, + ); + const order = ops.map((o) => (o.kind === 'put' ? o.store : o.kind)); + expect(order.indexOf('statements')).toBeGreaterThan( + order.indexOf('statusEvents'), + ); + }); + + it('keeps jobId on the last applications put when the site type is set', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + held('lever'), + ); + const job = (stores(ops, 'jobs')[0] as { record: Job }).record; + const apps = stores(ops, 'applications'); + expect(apps.length).toBeGreaterThan(1); + const last = (apps[apps.length - 1] as { record: Application }).record; + expect(last.jobId).toBe(job.id); + expect(last.siteType).toBe('lever'); + }); + + it('accepts a blank title and company and does not mutate data', () => { + const data = emptySnapshot(); + const { ops, record } = newApplicationFromFormOps( + data, + { source: 'paste', url: URL, title: ' ', companyName: '' }, + makeDeps(), + held(), + ); + expect(stores(ops, 'applications')).toHaveLength(1); + expect(stores(ops, 'companies')).toHaveLength(0); + expect(record?.missing).toBe(false); + expect(data.jobs).toHaveLength(0); + expect(data.applications).toHaveLength(0); + expect(data.statusEvents).toHaveLength(0); + }); +}); diff --git a/core/src/form-application.ts b/core/src/form-application.ts new file mode 100644 index 0000000..14eb3d4 --- /dev/null +++ b/core/src/form-application.ts @@ -0,0 +1,63 @@ +import type { FillResult } from './fill/result'; +import { fillRecordOps, type FillRecord } from './fill-records'; +import { formUrlKey } from './form-link'; +import { + createApplicationFromJobOps, + saveJobOps, + type JobInput, +} from './job-ops'; +import type { WriteOp } from './repository'; +import type { Deps, Id, Job, Snapshot } from './types'; + +/** + * A job, an application from it and, with a held fill result, the statements + * and site type that fill implies, as one op list for a single apply. + * Order: company (if new), job, application, status event, statements, site type. + */ +export function newApplicationFromFormOps( + data: Snapshot, + input: JobInput, + deps: Deps, + held?: FillResult, +): { ops: WriteOp[]; applicationId: Id; record?: FillRecord } { + const saved = saveJobOps(input, deps); + const jobPut = saved.ops[0]; + if (jobPut?.kind !== 'put' || jobPut.store !== 'jobs') { + throw new Error('saveJobOps returned no job put'); + } + const job: Job = { ...jobPut.record }; + if (typeof input.url === 'string') { + const key = formUrlKey(input.url, input.relCanonical); + if (key !== undefined) job.canonicalUrl = key; + } + const jobOp: WriteOp = { kind: 'put', store: 'jobs', record: job }; + + const created = createApplicationFromJobOps(job, data, deps); + const companyIndex = created.ops.findIndex( + (op) => op.kind === 'put' && op.store === 'companies', + ); + const ops: WriteOp[] = [...created.ops]; + ops.splice(companyIndex + 1, 0, jobOp); + + if (held === undefined) return { ops, applicationId: created.applicationId }; + + const next: Snapshot = { + ...data, + companies: [...data.companies], + jobs: [...data.jobs, job], + applications: [...data.applications], + statusEvents: [...data.statusEvents], + }; + for (const op of created.ops) { + if (op.kind !== 'put') continue; + if (op.store === 'companies') next.companies.push(op.record); + else if (op.store === 'applications') { + next.applications.push(op.record); + } else if (op.store === 'statusEvents') { + next.statusEvents.push(op.record); + } + } + const record = fillRecordOps(next, held, created.applicationId, deps); + ops.push(...record.ops); + return { ops, applicationId: created.applicationId, record }; +} From 93b05fc2b58530baf501f79b2350ab9f1b2ab39b Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:15:36 -0600 Subject: [PATCH 07/23] Match a job saved from a form's apply page --- core/src/form-link.test.ts | 13 +++++++++++++ core/src/form-link.ts | 8 +++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/core/src/form-link.test.ts b/core/src/form-link.test.ts index 0a8776a..6b2875b 100644 --- a/core/src/form-link.test.ts +++ b/core/src/form-link.test.ts @@ -123,6 +123,19 @@ describe('findApplicationsForForm', () => { expect(findApplicationsForForm(data, KEY)).toEqual([]); expect(findApplicationsForForm(data, 'x')).toEqual([]); }); + + it('matches a job saved from the Lever apply page', () => { + const applyUrl = 'https://jobs.lever.co/acme/123/apply'; + const data = snap({ + jobs: [ + { id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: applyUrl }, + ], + applications: [app('a1', '02', { jobId: 'j1' })], + }); + expect( + findApplicationsForForm(data, formUrlKey(applyUrl) as string), + ).toEqual(['a1']); + }); }); describe('linkFormOps', () => { diff --git a/core/src/form-link.ts b/core/src/form-link.ts index d4a29ec..bdc0310 100644 --- a/core/src/form-link.ts +++ b/core/src/form-link.ts @@ -70,9 +70,11 @@ export function findApplicationsForForm(data: Snapshot, key: string): Id[] { .sort(newestFirst); const byForm = active.filter((a) => formUrlsOf(a).includes(key)); - const byJob = active.filter( - (a) => typeof a.jobId === 'string' && jobUrls.get(a.jobId) === key, - ); + const byJob = active.filter((a) => { + if (typeof a.jobId !== 'string') return false; + const url = jobUrls.get(a.jobId); + return url !== undefined && (formUrlKey(url) ?? url) === key; + }); const byUrl = active.filter( (a) => typeof a.url === 'string' && formUrlKey(a.url) === key, ); From 09c4550e8c71810d21ef28f56218c9b109d91dc0 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:43:42 -0600 Subject: [PATCH 08/23] Link a form to its application in the popup --- shell/ui/FormLink.tsx | 171 ++++++++++++++++++++++++++++++++ shell/ui/Popup.tsx | 99 ++++++++++++++++++ shell/ui/theme/popup-layout.css | 17 ++++ 3 files changed, 287 insertions(+) create mode 100644 shell/ui/FormLink.tsx diff --git a/shell/ui/FormLink.tsx b/shell/ui/FormLink.tsx new file mode 100644 index 0000000..38be968 --- /dev/null +++ b/shell/ui/FormLink.tsx @@ -0,0 +1,171 @@ +import type { VNode } from 'preact'; +import { useState } from 'preact/hooks'; +import { applicationRows } from '../../core/src/application-list'; +import type { Id, Snapshot } from '../../core/src/types'; +import { Button } from './components/Button'; +import { Field } from './components/Field'; +import { Text } from './components/Text'; + +const MAX_ROWS = 20; + +type Mode = 'idle' | 'choose' | 'new'; + +function nameOf(value: string | undefined, fallback: string): string { + return value !== undefined && value.trim() !== '' ? value : fallback; +} + +/** + * Candidate application ids for the picker: active applications, newest + * created first. + */ +export function pickerCandidates(data: Snapshot): Id[] { + return applicationRows(data) + .filter((r) => !r.archived) + .sort((a, b) => + a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0, + ) + .map((r) => r.id); +} + +export function FormLink(props: { + data: Snapshot; + linkedId?: Id; + candidates: Id[]; + initialCompany?: string; + initialTitle?: string; + /** Resolves true when the write succeeded. */ + onLink: (id: Id) => Promise; + onNew: (input: { companyName: string; title: string }) => Promise; + busy: boolean; + error?: string; +}): VNode { + const [mode, setMode] = useState('idle'); + const [query, setQuery] = useState(''); + const [company, setCompany] = useState(undefined); + const [title, setTitle] = useState(undefined); + + const rows = applicationRows(props.data); + const byId = new Map(rows.map((r) => [r.id, r] as const)); + const label = (id: Id): string => { + const row = byId.get(id); + return `${nameOf(row?.companyName, 'Unknown company')} · ${nameOf(row?.title, 'Untitled')}`; + }; + + const done = (ok: boolean): void => { + if (ok) setMode('idle'); + }; + + let panel: VNode | null = null; + if (mode === 'choose') { + const needle = query.trim().toLowerCase(); + const matching = props.candidates.filter((id) => { + if (needle === '') return true; + const row = byId.get(id); + return ( + (row?.companyName ?? '').toLowerCase().includes(needle) || + (row?.title ?? '').toLowerCase().includes(needle) + ); + }); + panel = ( + + ); + } else if (mode === 'new') { + const companyValue = company ?? props.initialCompany ?? ''; + const titleValue = title ?? props.initialTitle ?? ''; + panel = ( + + ); + } + + const linked = props.linkedId !== undefined; + return ( + + ); +} diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index e237910..1f65d30 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -8,7 +8,15 @@ import { saveJobOps, } from '../../core/src/job-ops'; import type { JobInput } from '../../core/src/job-ops'; +import { newApplicationFromFormOps } from '../../core/src/form-application'; +import { + findApplicationsForForm, + formUrlKey, + linkFormOps, +} from '../../core/src/form-link'; import { profileValues } from '../../core/src/profile'; +import type { WriteOp } from '../../core/src/repository'; +import type { Id, Snapshot } from '../../core/src/types'; import { canonicalizeUrl } from '../../core/src/url'; import { capturePage } from '../capture/inject'; import type { CaptureOutcome } from '../capture/inject'; @@ -18,6 +26,7 @@ import { openDashboard } from '../open-dashboard'; import { useAppData } from './app-data'; import { AnyoneHere } from './AnyoneHere'; import { FillSection } from './FillSection'; +import { FormLink, pickerCandidates } from './FormLink'; import { Button } from './components/Button'; import { Fact } from './components/Fact'; import { Field } from './components/Field'; @@ -115,6 +124,18 @@ export function Popup(): VNode { } const controller = controllerRef.current; + const [fillStatus, setFillStatus] = useState(() => controller.state().status); + useEffect(() => { + const unsubscribe = controller.subscribe((s) => setFillStatus(s.status)); + setFillStatus(controller.state().status); + return unsubscribe; + }, [controller]); + + // Set by Choose… and Create and link; see linkedId below. + const [chosenId, setChosenId] = useState(undefined); + const [linking, setLinking] = useState(false); + const [linkError, setLinkError] = useState(undefined); + useEffect(() => { controller.refresh(); }, [data]); @@ -208,6 +229,71 @@ export function Popup(): VNode { const outcomeUrl = outcome.ok ? outcome.capture.url : outcome.url; const linkValue = pasteLink ?? (isHttp(outcomeUrl) ? outcomeUrl.trim() : ''); + const formKey = + outcomeUrl === undefined + ? undefined + : formUrlKey(outcomeUrl, captured?.relCanonical); + // A chosen application that still exists wins; otherwise the first match. + // Task 8 records a fill to linkedId; Task 9 shows a panel for it. + const linkedId: Id | undefined = + chosenId !== undefined && data.applications.some((a) => a.id === chosenId) + ? chosenId + : formKey === undefined + ? undefined + : findApplicationsForForm(data, formKey)[0]; + + // One apply per write; Task 8 adds the held fill result to these builders. + const linkOps = (d: Snapshot, id: Id): WriteOp[] => + linkFormOps(d, id, formKey ?? ''); + const runLink = ( + build: (d: Snapshot) => { ops: WriteOp[]; id: Id }, + ): Promise => { + setLinking(true); + setLinkError(undefined); + let id: Id | undefined; + return app + .apply((d) => { + const built = build(d); + id = built.id; + return built.ops; + }) + .then( + () => { + setChosenId(id); + setLinking(false); + return true; + }, + (err: unknown) => { + setLinkError(messageOf(err)); + setLinking(false); + return false; + }, + ); + }; + const linkExisting = (id: Id): Promise => + runLink((d) => ({ ops: linkOps(d, id), id })); + const linkNew = (names: { + companyName: string; + title: string; + }): Promise => + runLink((d) => { + const input: JobInput = { + source: captured + ? captured.source === 'jsonld' + ? 'jsonld' + : 'selection' + : 'paste', + url: isHttp(outcomeUrl) ? outcomeUrl.trim() : undefined, + relCanonical: captured?.relCanonical, + title: names.title, + companyName: names.companyName, + location: captured?.location, + text: captured?.text ?? '', + }; + const built = newApplicationFromFormOps(d, input, deps); + return { ops: built.ops, id: built.applicationId }; + }); + let body: VNode; if (captured) { const input: JobInput = { @@ -367,6 +453,19 @@ export function Popup(): VNode { ) : null} + {fillStatus === 'ready' && formKey !== undefined ? ( + + ) : null} @@ -125,7 +165,7 @@ export function FormLink(props: { > Create and link - @@ -141,7 +181,7 @@ export function FormLink(props: { + {typeof s.question === 'string' && + s.question.trim() !== '' ? ( +
They asked: {s.question}
+ ) : null} + {s.source === 'fill' ? ( + From a fill + ) : null} {check === 'mismatch' ? ( Differs from your answer: {canonical}{' '} From 29e7153f812be85958f46f2878f8548bfbe24a26 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:02:57 -0600 Subject: [PATCH 15/23] Document what a fill records --- README.md | 4 ++-- docs/ARCHITECTURE.md | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e8e383f..61212e7 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,12 @@ Stage 1 is the dashboard. Stage 2 adds saving a job from the page you are on, pl - **Applications list** with search, filters, manual entry, and a next-action date and who acts next. - **Save a job.** After you click the toolbar button (or press Alt+Shift+S by default; you can rebind it in about:addons), the popup reads the current tab once and offers the job for saving. Nothing is read before the click. -- **Fill a form.** In the popup, Fill writes your saved details and answers into the empty fields it recognises with certainty, then lists what it did not fill and why. It never changes a field that already has a value, and it never submits. Custom dropdowns and file uploads are listed for you to do yourself. +- **Fill a form.** In the popup, Fill writes your saved details and answers into the empty fields it recognises with certainty, then lists what it did not fill and why. It never changes a field that already has a value, and it never submits. Custom dropdowns and file uploads are listed for you to do yourself. When the form is linked to an application, the answers it filled are recorded as what you told them, with the form's question, and you can tick the ones you pasted yourself and mark the application Applied. - **Duplicate and repost facts.** When a job matches an application you already have, the popup says so ("already applied" or "possible match"). It also states the fact when you saved the same posting earlier, without judging it. - **Automatic backup.** Countersign saves `Countersign/countersign-backup.json` to your downloads folder, and the dashboard shows how old the last backup is. The backup file holds all your data, including your details and contacts, as plain text, so keep your downloads folder out of cloud sync if that matters to you. - **What I told them.** Per application, record the answers you gave. A warning appears when one differs from your canonical answer. - **Quiet list** (`#/quiet`) of applications with no response for a set number of days (a setting). You can close several at once. -- **Fill log.** On an application, record the application site type and how filling went. You enter it by hand. +- **Fill log.** On an application, record the application site type and how filling went. The site type is set by a fill when empty; how filling went is still yours to enter. - **Contacts** (`#/contacts`) with a log of reaching out, replies and referrals. The popup and the application page ask "anyone here?" and let you record that you checked and nobody was there. - **Deadlines** (`#/deadlines`): open tasks, next-action dates and quiet applications on one list, dated rows first. - **My details** (`#/details`): 14 profile fields (name, first and last name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fde58ba..9f255ed 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -27,6 +27,8 @@ The repository interface (`core/src/repository.ts`) has three methods: To change data, a function in `core/` takes a snapshot and returns a list of operations. It does not write anything itself. The shell applies the list. Views filter the snapshot in memory; the data set is hundreds of records, so there are no secondary indexes. +A fill's result is recorded by `core/src/fill-records.ts` in one write; nothing else about a fill is stored. + Two details in the shell: - Writes are serialised and each is built from a fresh snapshot (`shell/ui/write-queue.ts`). Two quick clicks cannot overwrite each other with stale data. @@ -40,6 +42,7 @@ An in-memory repository (`core/src/memory-repository.ts`) is used in tests. The - A round (`Round`) belongs to an application and holds a kind, date, time, interviewer ids and four flat debrief fields. A story (`Story`) holds situation, task, action, result and tags. A weekly review (`WeeklyReview`) holds a week start, an outreach target and an application cap. - New optional fields: `Company.isTarget`, `Application.projectsShown`, `Contact.followUpOn`, `Contact.followUpApplicationId` and `ContactEvent.voidedAt`. A contact event is undone by setting `voidedAt`; voided events are hidden and never counted. +- Optional fields for fills: `Statement.source` (`'fill'` when a fill recorded it), `Statement.question` (the form's question text) and `Application.formUrls` (the form pages linked to this application). - Weekly counts (`core/src/weekly.ts`) are derived on read from live contact events and status events whose date falls in Monday to Sunday. Nothing is stored except the plan. - `Company.anyoneHere` is `'checked_nobody'` when you have recorded that nobody you know works there. Contacts are otherwise linked by `companyId`. From 86fd8a519c695a6c7b5fbd0a586f99cd66d0177c Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:07:31 -0600 Subject: [PATCH 16/23] Hide a blank question in the interview pack --- core/src/pack.test.ts | 13 ++++++++++++- core/src/pack.ts | 8 ++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/core/src/pack.test.ts b/core/src/pack.test.ts index 90c7a43..78cd4f2 100644 --- a/core/src/pack.test.ts +++ b/core/src/pack.test.ts @@ -234,16 +234,27 @@ describe('interviewPack', () => { source: 'other', question: 42, }, + { + id: 's4', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsor', + value: { type: 'text', value: 'No' }, + source: 'fill', + question: ' ', + }, ], }); const pack = interviewPack(data, 'a1', {}); - const [first, second, third] = pack?.statements ?? []; + const [first, second, third, fourth] = pack?.statements ?? []; expect(first?.fromFill).toBe(true); expect(first?.question).toBe('Will you require sponsorship?'); expect(second?.fromFill).toBe(false); expect(second && 'question' in second).toBe(false); expect(third?.fromFill).toBe(false); expect(third && 'question' in third).toBe(false); + expect(fourth?.fromFill).toBe(true); + expect(fourth && 'question' in fourth).toBe(false); }); it('lists rounds in order with resolved interviewers and kind labels', () => { diff --git a/core/src/pack.ts b/core/src/pack.ts index 8880d62..ec5344f 100644 --- a/core/src/pack.ts +++ b/core/src/pack.ts @@ -118,8 +118,12 @@ export function interviewPack( result, }; if (answer) item.canonical = formatAnswer(answer.value); - const question = nonEmpty(statement.question); - if (question !== undefined) item.question = question; + if ( + typeof statement.question === 'string' && + statement.question.trim() !== '' + ) { + item.question = statement.question; + } if (result === 'mismatch') pack.unresolved += 1; pack.statements.push(item); } From e2fce29e0f91e9dc51c1212c50ab813593fdfd07 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:19:43 -0600 Subject: [PATCH 17/23] Show the duplicate and repost facts when making an application from a form --- core/src/form-application.test.ts | 43 +++++++++++++++++++++++++++++++ core/src/form-application.ts | 38 ++++++++++++++++++++++++--- shell/ui/Popup.tsx | 28 ++++++++++++++++++++ 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/core/src/form-application.test.ts b/core/src/form-application.test.ts index 6704ecc..2d0df10 100644 --- a/core/src/form-application.test.ts +++ b/core/src/form-application.test.ts @@ -50,6 +50,49 @@ function stores(ops: WriteOp[], store: string): WriteOp[] { return ops.filter((o) => o.kind === 'put' && o.store === store); } +describe('newApplicationFromFormOps facts', () => { + const archivedJob: Job = { + id: 'oldjob', + source: 'paste', + title: 'Dev', + companyName: 'Acme', + canonicalUrl: 'https://jobs.lever.co/acme/1', + createdAt: '2025-12-01T00:00:00.000Z', + } as Job; + + it('reports a duplicate and a repost of an earlier job at the form key', () => { + const data: Snapshot = { + ...emptySnapshot(), + jobs: [archivedJob], + applications: [ + { + id: 'oldapp', + jobId: 'oldjob', + title: 'Dev', + createdAt: '2025-12-01T00:00:00.000Z', + } as Application, + ], + }; + const built = newApplicationFromFormOps( + data, + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + expect(built.match).toBe('already_applied'); + expect(built.repost).toMatch(/^You saved this posting on /); + }); + + it('reports nothing for a new posting and never counts itself', () => { + const built = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + expect(built.match).toBeUndefined(); + expect(built.repost).toBeUndefined(); + }); +}); + describe('newApplicationFromFormOps', () => { it('makes one job and one linked interested application', () => { const { ops, applicationId, record } = newApplicationFromFormOps( diff --git a/core/src/form-application.ts b/core/src/form-application.ts index 28c8c74..f21f9fb 100644 --- a/core/src/form-application.ts +++ b/core/src/form-application.ts @@ -1,3 +1,10 @@ +import { toLocalDate } from './dates'; +import { + findApplicationMatch, + repostFact, + type ApplicationMatch, + type JobCandidate, +} from './duplicates'; import type { FillResult } from './fill/result'; import { fillRecordOps, type FillRecord } from './fill-records'; import { formUrlKey, linkFormOps } from './form-link'; @@ -48,7 +55,13 @@ export function newApplicationFromFormOps( input: JobInput, deps: Deps, held?: FillResult, -): { ops: WriteOp[]; applicationId: Id; record?: FillRecord } { +): { + ops: WriteOp[]; + applicationId: Id; + record?: FillRecord; + match?: ApplicationMatch['kind']; + repost?: string; +} { const saved = saveJobOps(input, deps); const jobPut = saved.ops[0]; if (jobPut?.kind !== 'put' || jobPut.store !== 'jobs') { @@ -68,7 +81,26 @@ export function newApplicationFromFormOps( const ops: WriteOp[] = [...created.ops]; ops.splice(companyIndex + 1, 0, jobOp); - if (held === undefined) return { ops, applicationId: created.applicationId }; + // Facts only inform, as in Save job: computed on the data before this write, + // for a candidate stored the way the job is (form key as its canonical URL). + const candidate: JobCandidate = {}; + if (job.canonicalUrl !== undefined) candidate.canonicalUrl = job.canonicalUrl; + if (job.companyName !== undefined) candidate.companyName = job.companyName; + if (job.title !== undefined) candidate.title = job.title; + const match = findApplicationMatch(data, candidate)?.kind; + const repost = repostFact( + data, + { ...candidate, excludeJobId: job.id }, + toLocalDate(new Date(deps.now())), + )?.text; + const facts = { + ...(match !== undefined ? { match } : {}), + ...(repost !== undefined ? { repost } : {}), + }; + + if (held === undefined) { + return { ops, applicationId: created.applicationId, ...facts }; + } const next: Snapshot = { ...data, @@ -88,5 +120,5 @@ export function newApplicationFromFormOps( } const record = fillRecordOps(next, held, created.applicationId, deps); ops.push(...record.ops); - return { ops, applicationId: created.applicationId, record }; + return { ops, applicationId: created.applicationId, record, ...facts }; } diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index c5f56d1..dbe9534 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -155,6 +155,10 @@ export function Popup(): VNode { const [recordNotice, setRecordNotice] = useState( undefined, ); + // Duplicate and repost facts for the application just made from this form. + const [newFacts, setNewFacts] = useState< + { match: Facts['match']; repost: string | undefined } | undefined + >(undefined); const linkingRef = useRef(false); const linkedIdRef = useRef(undefined); @@ -289,6 +293,8 @@ export function Popup(): VNode { id: Id; name: string; record?: FillRecord; + match?: Facts['match']; + repost?: string; }, ): Promise => { if (linkingRef.current) return Promise.resolve(false); @@ -300,6 +306,8 @@ export function Popup(): VNode { name: string; record?: FillRecord; held?: FillResult; + match?: Facts['match']; + repost?: string; } = { name: '' }; return app .apply((d) => { @@ -309,6 +317,8 @@ export function Popup(): VNode { got.id = built.id; got.name = built.name; got.record = built.record; + got.match = built.match; + got.repost = built.repost; if (built.record?.missing) throw new Error(MISSING); return built.ops; }) @@ -317,6 +327,11 @@ export function Popup(): VNode { linkingRef.current = false; setChosenId(got.id); setLinking(false); + setNewFacts( + got.match !== undefined || got.repost !== undefined + ? { match: got.match, repost: got.repost } + : undefined, + ); if (got.record !== undefined) { // Clear only the result this link recorded; a Fill that finished // during the write has replaced it and must survive. @@ -425,6 +440,8 @@ export function Popup(): VNode { id: built.applicationId, name: displayName(names.companyName, names.title), record: built.record, + match: built.match, + repost: built.repost, }; }); @@ -604,6 +621,17 @@ export function Popup(): VNode { recordLine={recordLine} /> ) : null} + {newFacts?.match === 'already_applied' ? ( + Already applied here. + ) : null} + {newFacts?.match === 'possible_match' ? ( + + Possible match: an application for the same company and title. + + ) : null} + {newFacts?.repost ? ( + {newFacts.repost} + ) : null} {fillStatus === 'ready' && linkedId !== undefined ? ( Date: Sat, 21 Nov 2026 17:20:20 -0600 Subject: [PATCH 18/23] Match a job saved from a form when saving it again from the apply page --- core/src/duplicates.test.ts | 33 +++++++++++++++++++++++++++++++++ core/src/duplicates.ts | 13 +++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/core/src/duplicates.test.ts b/core/src/duplicates.test.ts index 9850c5e..92ab8f3 100644 --- a/core/src/duplicates.test.ts +++ b/core/src/duplicates.test.ts @@ -206,6 +206,39 @@ describe('findApplicationMatch', () => { }); }); +describe('form apply-page addresses', () => { + const stored = 'https://jobs.lever.co/example/abc'; + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-06-12${AT}`, canonicalUrl: stored }], + applications: [{ id: 'a1', createdAt: `2026-06-13${AT}`, jobId: 'j1' }], + }); + + it('findApplicationMatch matches the /apply address of a stored job', () => { + expect( + findApplicationMatch(data, { canonicalUrl: `${stored}/apply` }), + ).toEqual({ kind: 'already_applied', applicationId: 'a1' }); + expect( + findApplicationMatch(data, { + canonicalUrl: 'https://jobs.lever.co/example/other/apply', + }), + ).toBeUndefined(); + }); + + it('repostFact matches the /apply address of a stored job', () => { + expect( + repostFact(data, { canonicalUrl: `${stored}/apply` }, '2026-11-15') + ?.firstSavedOn, + ).toBe('2026-06-12'); + expect( + repostFact( + data, + { canonicalUrl: 'https://jobs.lever.co/example/other/apply' }, + '2026-11-15', + ), + ).toBeUndefined(); + }); +}); + describe('repostFact', () => { const job = (id: string, day: string, extra: Partial = {}): Job => ({ id, diff --git a/core/src/duplicates.ts b/core/src/duplicates.ts index 4259da0..735c4cf 100644 --- a/core/src/duplicates.ts +++ b/core/src/duplicates.ts @@ -1,5 +1,6 @@ import { normalizeName } from './application-ops'; import { isLocalDate, toLocalDate } from './dates'; +import { formUrlKey } from './form-link'; import type { Application, Id, Job, LocalDate, Snapshot } from './types'; import { canonicalizeUrl } from './url'; @@ -45,6 +46,14 @@ function safeCanonical(url: string): string | undefined { } } +// Equal, or both the same posting once a form's apply segment is dropped. +function urlsMatch(have: string | undefined, want: string): boolean { + if (have === undefined) return false; + if (have === want) return true; + const key = formUrlKey(want); + return key !== undefined && key === formUrlKey(have); +} + function applicationCanonicalUrl( app: Application, jobsById: Map, @@ -110,7 +119,7 @@ export function findApplicationMatch( const appTitle = nameKey(app.title); if ( wantUrl !== undefined && - url === wantUrl && + urlsMatch(url, wantUrl) && !contradicts(wantCompany, company, wantTitle, appTitle) ) { if ( @@ -169,7 +178,7 @@ export function repostFact( const jobTitle = nameKey(job.title); const sameUrl = wantUrl !== undefined && - str(job.canonicalUrl) === wantUrl && + urlsMatch(str(job.canonicalUrl), wantUrl) && !contradicts(wantCompany, jobCompany, wantTitle, jobTitle); const sameName = wantCompany !== undefined && From ce9957bbbf88c251b21d8d8a1ec68a090b1527fc Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:20:57 -0600 Subject: [PATCH 19/23] Keep a fill result the popup still offers to record --- shell/ui/Popup.tsx | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index dbe9534..6626fb7 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -160,6 +160,7 @@ export function Popup(): VNode { { match: Facts['match']; repost: string | undefined } | undefined >(undefined); const linkingRef = useRef(false); + const keepHeldRef = useRef(false); const linkedIdRef = useRef(undefined); useEffect(() => { @@ -169,11 +170,15 @@ export function Popup(): VNode { // A match linked the form without the owner's click: drop the stale held // fill rather than let a later Choose… record it. The owner's own link // path records and clears held itself, and is excluded while in flight. + // Exception: onFilled holds a result on two recoverable paths (application + // gone, write rejected) where the popup still offers to record it; those + // keep it until the owner's next link (runLink resets this). useEffect(() => { if ( linkedIdRef.current !== undefined && heldRef.current !== undefined && - !linkingRef.current + !linkingRef.current && + !keepHeldRef.current ) { heldRef.current = undefined; setHeld(undefined); @@ -299,6 +304,7 @@ export function Popup(): VNode { ): Promise => { if (linkingRef.current) return Promise.resolve(false); linkingRef.current = true; + keepHeldRef.current = false; setLinking(true); setLinkError(undefined); const got: { @@ -327,6 +333,7 @@ export function Popup(): VNode { linkingRef.current = false; setChosenId(got.id); setLinking(false); + setRecordNotice(undefined); setNewFacts( got.match !== undefined || got.repost !== undefined ? { match: got.match, repost: got.repost } @@ -338,7 +345,6 @@ export function Popup(): VNode { if (got.held !== undefined && heldRef.current === got.held) { setHeld(undefined); } - setRecordNotice(undefined); setRecordLine( got.record.recorded > 0 ? { @@ -398,12 +404,14 @@ export function Popup(): VNode { const record = got.record; if (record === undefined) return; if (record.missing) { + keepHeldRef.current = true; heldRef.current = result; setHeld(result); setChosenId(undefined); setRecordNotice(MISSING); return; } + keepHeldRef.current = false; setHeld(undefined); if (record.recorded > 0) { setRecordLine({ @@ -413,7 +421,12 @@ export function Popup(): VNode { }); } }, - (err: unknown) => setLinkError(messageOf(err)), + (err: unknown) => { + keepHeldRef.current = true; + heldRef.current = result; + setHeld(result); + setLinkError(messageOf(err)); + }, ); }; const linkNew = (names: { From a5336e9081c3e56da3de2fa9c00eeeda3a45135c Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:21:00 -0600 Subject: [PATCH 20/23] Ignore overlong form URLs --- core/src/form-link.test.ts | 9 +++++++++ core/src/form-link.ts | 3 +++ 2 files changed, 12 insertions(+) diff --git a/core/src/form-link.test.ts b/core/src/form-link.test.ts index 6b2875b..80c5b64 100644 --- a/core/src/form-link.test.ts +++ b/core/src/form-link.test.ts @@ -26,6 +26,15 @@ function app(id: string, day: string, extra: object = {}): Application { const KEY = 'https://example.com/jobs/1'; describe('formUrlKey', () => { + it('ignores an address longer than the capture cap', () => { + const long = `https://example.com/${'a'.repeat(8_001 - 20)}`; + expect(long).toHaveLength(8_001); + expect(formUrlKey(long)).toBeUndefined(); + expect(formUrlKey('https://example.com/jobs/1')).toBe( + 'https://example.com/jobs/1', + ); + }); + it('strips the Lever apply segment', () => { expect(formUrlKey('https://jobs.lever.co/acme/123/apply')).toBe( formUrlKey('https://jobs.lever.co/acme/123'), diff --git a/core/src/form-link.ts b/core/src/form-link.ts index bdc0310..7e46f34 100644 --- a/core/src/form-link.ts +++ b/core/src/form-link.ts @@ -11,6 +11,8 @@ interface UrlLike { declare const URL: { new (url: string, base?: string): UrlLike }; export const MAX_FORM_URLS = 20; +// Matches the capture URL cap (shell/capture MAX_CAPTURE_URL); core cannot import it. +export const MAX_FORM_URL = 8_000; // Hosts whose application form lives one path segment below the posting. const TRAILING_SEGMENTS: Readonly> = { @@ -24,6 +26,7 @@ export function formUrlKey( url: string, relCanonical?: string, ): string | undefined { + if (url.length > MAX_FORM_URL) return undefined; try { const parsed = new URL(url.trim()); if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { From b2fac8dc35ee4459622f3cffc0b8d10e1fed8455 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:22:46 -0600 Subject: [PATCH 21/23] Drop unneeded casts in the form application tests --- core/src/form-application.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/form-application.test.ts b/core/src/form-application.test.ts index 2d0df10..62f58e7 100644 --- a/core/src/form-application.test.ts +++ b/core/src/form-application.test.ts @@ -58,7 +58,7 @@ describe('newApplicationFromFormOps facts', () => { companyName: 'Acme', canonicalUrl: 'https://jobs.lever.co/acme/1', createdAt: '2025-12-01T00:00:00.000Z', - } as Job; + }; it('reports a duplicate and a repost of an earlier job at the form key', () => { const data: Snapshot = { @@ -70,7 +70,7 @@ describe('newApplicationFromFormOps facts', () => { jobId: 'oldjob', title: 'Dev', createdAt: '2025-12-01T00:00:00.000Z', - } as Application, + }, ], }; const built = newApplicationFromFormOps( From a00d039ef93dc10231b159e6954eb763328e4acc Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:24:51 -0600 Subject: [PATCH 22/23] Keep a held fill result when the owner's link fails --- shell/ui/Popup.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index 6626fb7..9cdbfea 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -304,7 +304,6 @@ export function Popup(): VNode { ): Promise => { if (linkingRef.current) return Promise.resolve(false); linkingRef.current = true; - keepHeldRef.current = false; setLinking(true); setLinkError(undefined); const got: { @@ -331,6 +330,9 @@ export function Popup(): VNode { .then( () => { linkingRef.current = false; + // Only a successful owner link ends the keep; a failed one leaves + // the held result offered for a retry. + keepHeldRef.current = false; setChosenId(got.id); setLinking(false); setRecordNotice(undefined); @@ -388,6 +390,7 @@ export function Popup(): VNode { // Read when the fill completes, not at the click (FillSection is fixed). const id = linkedIdRef.current; if (id === undefined) { + keepHeldRef.current = false; setHeld(result); return; } From b6262e62591046f427a830aaa6f2000079133efd Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:24:53 -0600 Subject: [PATCH 23/23] Test the Ashby application page match --- core/src/duplicates.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/core/src/duplicates.test.ts b/core/src/duplicates.test.ts index 92ab8f3..848e7f9 100644 --- a/core/src/duplicates.test.ts +++ b/core/src/duplicates.test.ts @@ -224,6 +224,29 @@ describe('form apply-page addresses', () => { ).toBeUndefined(); }); + it('matches the Ashby /application address of a stored job', () => { + const ashby = 'https://jobs.ashbyhq.com/example/abc'; + const ashbyData = snap({ + jobs: [{ id: 'j2', createdAt: `2026-06-12${AT}`, canonicalUrl: ashby }], + applications: [{ id: 'a2', createdAt: `2026-06-13${AT}`, jobId: 'j2' }], + }); + expect( + findApplicationMatch(ashbyData, { canonicalUrl: `${ashby}/application` }), + ).toEqual({ kind: 'already_applied', applicationId: 'a2' }); + expect( + repostFact( + ashbyData, + { canonicalUrl: `${ashby}/application` }, + '2026-11-15', + )?.firstSavedOn, + ).toBe('2026-06-12'); + expect( + findApplicationMatch(ashbyData, { + canonicalUrl: 'https://jobs.ashbyhq.com/example/zzz/application', + }), + ).toBeUndefined(); + }); + it('repostFact matches the /apply address of a stored job', () => { expect( repostFact(data, { canonicalUrl: `${stored}/apply` }, '2026-11-15')