@hadoku/jobplatform-worker 2.32.77 → 2.32.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5500,260 +5500,19 @@ function registerFeedbackRoutes(app2) {
5500
5500
  }
5501
5501
  );
5502
5502
  }
5503
- async function loadTailoringFields(db, id) {
5504
- return db.prepare("SELECT title, company, description, location, workplace_type FROM jobs WHERE id = ?").bind(id).first();
5505
- }
5506
- function resumeViaEdge(env, path, init) {
5507
- if (!env.EDGE) throw new Error("EDGE service binding not configured");
5508
- const key = env.HADOKU_SERVICE_KEY?.trim();
5509
- if (!key) throw new Error("HADOKU_SERVICE_KEY not configured");
5510
- const headers = new Headers(init.headers);
5511
- headers.set("X-User-Key", key);
5512
- return env.EDGE.fetch(`${EDGE_BASE}${path}`, { ...init, headers });
5513
- }
5514
- async function callResumeBinding(env, path, payload) {
5515
- return resumeViaEdge(env, path, {
5516
- method: "POST",
5517
- headers: { "Content-Type": "application/json" },
5518
- body: JSON.stringify(payload)
5519
- });
5520
- }
5521
- async function fetchMintedResume(env, slug2) {
5522
- const res = await resumeViaEdge(env, `/resume/api/resume?v=${encodeURIComponent(slug2)}`, {
5523
- method: "GET"
5524
- });
5525
- if (!res.ok) return { expired: true };
5526
- const body = await res.json();
5527
- if (!body.variant || !body.content) return { expired: true };
5528
- return { markdown: body.content };
5529
- }
5530
- async function readOptions(c) {
5531
- try {
5532
- return await c.req.json();
5533
- } catch {
5534
- return {};
5503
+ function formUrl(job) {
5504
+ const own = job.id.slice(job.id.indexOf("_") + 1);
5505
+ if (job.slug && job.id.startsWith("greenhouse_") && /^\d+$/.test(own)) {
5506
+ return `https://job-boards.greenhouse.io/embed/job_app?for=${encodeURIComponent(job.slug)}&token=${own}`;
5535
5507
  }
5508
+ if (job.slug && job.id.startsWith("ashby_")) {
5509
+ return `https://jobs.ashbyhq.com/${encodeURIComponent(job.slug)}/${own}/application`;
5510
+ }
5511
+ if (job.slug && job.id.startsWith("lever_")) {
5512
+ return `https://jobs.lever.co/${encodeURIComponent(job.slug)}/${own}/apply`;
5513
+ }
5514
+ return job.url;
5536
5515
  }
5537
- function ownerNameOf(opts) {
5538
- return typeof opts.ownerName === "string" ? opts.ownerName : void 0;
5539
- }
5540
- function questionsOf(opts) {
5541
- if (!Array.isArray(opts.questions)) return void 0;
5542
- const questions = opts.questions.filter((q) => typeof q === "string" && q.trim() !== "").map((q) => q.trim().slice(0, 500)).slice(0, 25);
5543
- return questions.length ? questions : void 0;
5544
- }
5545
- const UPSTREAM_DETAIL_CHARS = 1500;
5546
- async function upstreamError(c, kind, jobId, res) {
5547
- const detail = (await res.text()).slice(0, UPSTREAM_DETAIL_CHARS);
5548
- recordEvent(c, {
5549
- level: "warn",
5550
- event: "tailoring.failed",
5551
- message: `${kind} for ${jobId}: resume-api ${res.status}`,
5552
- context: { kind, job_id: jobId, upstream_status: res.status, detail }
5553
- });
5554
- return {
5555
- success: false,
5556
- error: "Upstream error",
5557
- message: `resume-api ${res.status}: ${detail}`
5558
- };
5559
- }
5560
- function generated(c, kind, jobId, extra = {}) {
5561
- recordEvent(c, {
5562
- level: "info",
5563
- event: "tailoring.generated",
5564
- message: `${kind} for ${jobId}`,
5565
- context: { kind, job_id: jobId, ...extra }
5566
- });
5567
- }
5568
- function registerTailoringRoutes(app2) {
5569
- app2.post("/jobs/:id/resume", gateAuthed);
5570
- app2.post("/jobs/:id/cover-letter", gateAuthed);
5571
- app2.post("/jobs/:id/resume", async (c) => {
5572
- const id = c.req.param("id");
5573
- const opts = await readOptions(c);
5574
- const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
5575
- if (!job) {
5576
- return c.json(
5577
- { success: false, error: "Not found", message: `Job '${id}' not found` },
5578
- 404
5579
- );
5580
- }
5581
- const res = await callResumeBinding(c.env, "/resume/api/tailored-resume", {
5582
- job_title: job.title,
5583
- company: job.company,
5584
- description: job.description,
5585
- ...typeof opts.profile_type === "string" ? { profile_type: opts.profile_type } : {},
5586
- ...typeof opts.tailor === "boolean" ? { tailor: opts.tailor } : {}
5587
- });
5588
- if (!res.ok) return c.json(await upstreamError(c, "resume", id, res), 502);
5589
- const data = await res.json();
5590
- generated(c, "resume", id);
5591
- return c.json({ success: true, data }, 200);
5592
- });
5593
- app2.post("/jobs/:id/cover-letter", async (c) => {
5594
- const id = c.req.param("id");
5595
- const opts = await readOptions(c);
5596
- const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
5597
- if (!job) {
5598
- return c.json(
5599
- { success: false, error: "Not found", message: `Job '${id}' not found` },
5600
- 404
5601
- );
5602
- }
5603
- const res = await callResumeBinding(c.env, "/resume/api/cover-letter", {
5604
- job_title: job.title,
5605
- company: job.company,
5606
- description: job.description,
5607
- ...opts.tone === "formal" || opts.tone === "conversational" ? { tone: opts.tone } : {}
5608
- });
5609
- if (!res.ok) return c.json(await upstreamError(c, "cover_letter", id, res), 502);
5610
- const data = await res.json();
5611
- generated(c, "cover_letter", id);
5612
- return c.json({ success: true, data }, 200);
5613
- });
5614
- app2.post("/jobs/:id/packet-link", gateAuthed);
5615
- app2.post("/jobs/:id/packet-link", async (c) => {
5616
- const id = c.req.param("id");
5617
- const opts = await readOptions(c);
5618
- const resumeMarkdown = typeof opts.resume_markdown === "string" ? opts.resume_markdown : "";
5619
- if (!resumeMarkdown) {
5620
- return c.json(
5621
- { success: false, error: "Bad request", message: "resume_markdown is required" },
5622
- 400
5623
- );
5624
- }
5625
- const coverLetterMarkdown = typeof opts.cover_letter_markdown === "string" ? opts.cover_letter_markdown : void 0;
5626
- const ttlDays = typeof opts.ttl_days === "number" ? opts.ttl_days : 365;
5627
- const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
5628
- if (!job) {
5629
- return c.json(
5630
- { success: false, error: "Not found", message: `Job '${id}' not found` },
5631
- 404
5632
- );
5633
- }
5634
- const who = await effectiveUserId(c, ownerNameOf(opts));
5635
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
5636
- const res = await callResumeBinding(c.env, "/resume/api/variants", {
5637
- label: `${job.company} — ${job.title}`,
5638
- markdown: resumeMarkdown,
5639
- ...coverLetterMarkdown ? { cover_letter_markdown: coverLetterMarkdown } : {},
5640
- company: job.company,
5641
- job_title: job.title,
5642
- ttl_days: ttlDays
5643
- });
5644
- if (!res.ok) return c.json(await upstreamError(c, "packet_link", id, res), 502);
5645
- const variant = await res.json();
5646
- if (!variant.slug) {
5647
- return c.json(
5648
- {
5649
- success: false,
5650
- error: "Upstream error",
5651
- message: "resume-api returned no slug"
5652
- },
5653
- 502
5654
- );
5655
- }
5656
- const now = (/* @__PURE__ */ new Date()).toISOString();
5657
- const db = c.env.JOB_PLATFORM_DB;
5658
- await db.batch([
5659
- db.prepare(
5660
- `INSERT INTO job_events
5661
- (job_id, user_id, kind, from_state, to_state, note, occurred_at, created_at)
5662
- SELECT ?1, ?2, 'state', NULL, 'saved', NULL, ?3, ?3
5663
- WHERE NOT EXISTS (SELECT 1 FROM job_states WHERE job_id = ?1 AND user_id = ?2)`
5664
- ).bind(id, who.userId, now),
5665
- db.prepare(
5666
- `INSERT INTO job_states (job_id, user_id, state, notes, updated_at, variant_slug)
5667
- VALUES (?, ?, 'saved', NULL, ?, ?)
5668
- ON CONFLICT (job_id, user_id) DO UPDATE SET
5669
- variant_slug = excluded.variant_slug,
5670
- updated_at = excluded.updated_at`
5671
- ).bind(id, who.userId, now, variant.slug)
5672
- ]);
5673
- const url = `https://hadoku.me/resume?v=${encodeURIComponent(variant.slug)}`;
5674
- generated(c, "packet_link", id, { slug: variant.slug, user_id: who.userId });
5675
- return c.json({ success: true, data: { slug: variant.slug, url } }, 200);
5676
- });
5677
- app2.post("/jobs/:id/application-extras", gateAuthed);
5678
- app2.post("/jobs/:id/application-extras", async (c) => {
5679
- const id = c.req.param("id");
5680
- const opts = await readOptions(c);
5681
- let resumeMarkdown = typeof opts.resume_markdown === "string" ? opts.resume_markdown : "";
5682
- if (!resumeMarkdown) {
5683
- const who = await effectiveUserId(c, ownerNameOf(opts));
5684
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
5685
- const userId = who.userId;
5686
- const row = userId ? await c.env.JOB_PLATFORM_DB.prepare(
5687
- "SELECT variant_slug FROM job_states WHERE job_id = ? AND user_id = ?"
5688
- ).bind(id, userId).first() : null;
5689
- const slug2 = row?.variant_slug ?? null;
5690
- if (!slug2) {
5691
- return c.json(
5692
- {
5693
- success: false,
5694
- error: "Bad request",
5695
- message: "resume_markdown is required, or prepare a packet for this job first — no minted packet was found for this caller."
5696
- },
5697
- 400
5698
- );
5699
- }
5700
- const minted = await fetchMintedResume(c.env, slug2);
5701
- if ("expired" in minted) {
5702
- return c.json(
5703
- {
5704
- success: false,
5705
- error: "Bad request",
5706
- message: `The packet for this job ('${slug2}') has expired; re-prepare it or post resume_markdown.`
5707
- },
5708
- 400
5709
- );
5710
- }
5711
- resumeMarkdown = minted.markdown;
5712
- }
5713
- const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
5714
- if (!job) {
5715
- return c.json(
5716
- { success: false, error: "Not found", message: `Job '${id}' not found` },
5717
- 404
5718
- );
5719
- }
5720
- const res = await callResumeBinding(c.env, "/resume/api/application-extras", {
5721
- job_title: job.title,
5722
- company: job.company,
5723
- description: job.description,
5724
- resume_markdown: resumeMarkdown,
5725
- // The kit's location answers must speak to THIS job's location, not the
5726
- // candidate's default metro — resume-api injects these into its prompt.
5727
- job_location: job.location ?? void 0,
5728
- workplace_type: job.workplace_type ?? void 0,
5729
- questions: questionsOf(opts)
5730
- });
5731
- if (!res.ok) return c.json(await upstreamError(c, "application_extras", id, res), 502);
5732
- const data = await res.json();
5733
- generated(c, "application_extras", id);
5734
- return c.json({ success: true, data }, 200);
5735
- });
5736
- }
5737
- const COMMON_QUESTIONS = [
5738
- { question: "Veteran Status", seenOn: 15 },
5739
- { question: "Disability Status", seenOn: 13 },
5740
- { question: "Are you Hispanic/Latino?", seenOn: 13 },
5741
- { question: "Location (City)", seenOn: 12 },
5742
- { question: "Preferred First Name", seenOn: 11 },
5743
- { question: "How did you hear about this job?", seenOn: 6 },
5744
- { question: "Are you legally authorized to work in the United States?", seenOn: 3 },
5745
- {
5746
- question: "Are you legally authorized to work in the country where the job is located?",
5747
- seenOn: 2
5748
- },
5749
- {
5750
- question: "Will you now or in the future require company sponsorship to retain or extend your work authorization?",
5751
- seenOn: 2
5752
- },
5753
- { question: "I identify my gender as", seenOn: 2 },
5754
- { question: "Are you at least 18 years of age?", seenOn: 1 },
5755
- { question: "Agreement to Arbitrate", seenOn: 1 }
5756
- ];
5757
5516
  function questionKey(text) {
5758
5517
  return text.replace(/\*/g, " ").toLowerCase().replace(/n't\b/g, " not ").replace(/[^a-z0-9]+/g, " ").trim();
5759
5518
  }
@@ -5814,411 +5573,101 @@ function questionNegated(terms) {
5814
5573
  for (const t of terms) if (NEGATIONS.has(t)) return true;
5815
5574
  return false;
5816
5575
  }
5817
- const FOREIGN = /\b(canada|canadian|quebec|ireland|irish|uk|united kingdom|britain|england|scotland|germany|france|india|australia|mexico|brazil|japan|singapore|netherlands|spain|israel|poland|china|emea|europe|apac|latam)\b/;
5818
- const LEGAL = /\b(agree|agreement|certify|consent|acknowledge|arbitrat\w*|privacy|terms of service|confirm receipt|attest|personal data)\b/;
5819
- const CONDITIONAL = /^if\b|\bif you (do|did|selected|answered|chose|said|have|are|were)\b|\bplease (list|share|explain|describe|specify|provide)\b/;
5820
- function isFollowUp(question) {
5821
- return /^if\b|\bif you (do|did|selected|answered|chose|said)\b/.test(questionKey(question));
5822
- }
5823
- const RULES = [
5824
- {
5825
- id: "sponsorship",
5826
- label: "Visa sponsorship",
5827
- match: (h) => /\bsponsor/.test(h) || /\b(visa|immigration)\b/.test(h) && /\b(require|need)\b/.test(h),
5828
- sensitive: true
5829
- },
5830
- {
5831
- id: "work_authorization",
5832
- label: "Authorized to work",
5833
- match: (h) => /\b(authori[sz]ed|eligible|entitled|right)\b/.test(h) && /\bto work\b/.test(h),
5834
- sensitive: true
5835
- },
5836
- {
5837
- id: "race_ethnicity",
5838
- label: "Race / ethnicity",
5839
- match: (h) => /\b(race|racial|ethnicity|ethnic)\b/.test(h),
5840
- sensitive: false
5841
- },
5842
- {
5843
- id: "hispanic_latino",
5844
- label: "Hispanic / Latino",
5845
- match: (h) => /\b(hispanic|latino|latina|latinx)\b/.test(h),
5846
- sensitive: false
5847
- },
5848
- {
5849
- id: "veteran",
5850
- label: "Veteran status",
5851
- match: (h) => /\b(veteran|military|armed forces)\b/.test(h),
5852
- sensitive: false
5853
- },
5854
- { id: "disability", label: "Disability", match: (h) => /\bdisabilit/.test(h), sensitive: false },
5855
- { id: "lgbtq", label: "LGBTQ+", match: (h) => /\blgbt/.test(h), sensitive: false },
5856
- {
5857
- id: "current_employer",
5858
- label: "Current employer",
5859
- // "current", not "currently": "Are you currently employed by an Aledade
5860
- // Partner Practice?" is a different question with a different answer.
5861
- //
5862
- // ADJACENT words, not "current … company" anywhere. The loose form put
5863
- // "Are you a current government official or … a company …" in this
5864
- // family, and its answer — "No, I am not a current or former Government
5865
- // Official" — would have been offered for Most Recent Employer.
5866
- match: (h) => /\b(current|most recent)( most recent)? (employer|company)\b/.test(h),
5867
- sensitive: false
5868
- },
5869
- {
5870
- id: "current_title",
5871
- label: "Current job title",
5872
- match: (h) => /\b(current|most recent)( most recent)? (job )?title\b/.test(h),
5873
- sensitive: false
5874
- },
5875
- {
5876
- id: "state_of_residence",
5877
- label: "State you live in",
5878
- // Not "plan": "the state you plan to be located in" asks about the
5879
- // future, and may well differ.
5880
- match: (h) => /\bstate\b/.test(h) && /\b(reside|live|currently)\b/.test(h) && !/\bplan\b/.test(h),
5881
- sensitive: false
5882
- },
5883
- {
5884
- id: "postal_code",
5885
- label: "ZIP / postal code",
5886
- match: (h) => /\b(zip|postal)\b/.test(h),
5887
- sensitive: false
5888
- },
5889
- {
5890
- id: "current_city",
5891
- label: "Where you live",
5892
- match: (h) => /\b(current|currently)\b/.test(h) && /\blocat/.test(h) || /\blocation city\b/.test(h),
5893
- sensitive: false
5894
- },
5895
- {
5896
- id: "how_heard",
5897
- label: "How you heard about the role",
5898
- match: (h) => /\bhow did you (first )?(hear|learn|find)\b/.test(h) || /\bwhere (have|did) you (hear|heard|learn|learned)\b/.test(h),
5899
- sensitive: false
5900
- },
5901
- {
5902
- id: "worked_here_before",
5903
- label: "Worked at this company before",
5904
- // A fact about EACH employer, so the dashboard lists every company and
5905
- // the owner unticks any they did work for. Grouped because the answer is
5906
- // "no" for every employer they never worked at, which is nearly all.
5907
- match: (h) => /\b(previously|formerly|ever|before)\b/.test(h) && /\b(employed|worked)\b/.test(h) || /\bformer\b.*\bemployee\b/.test(h),
5908
- sensitive: false
5909
- },
5910
- {
5911
- id: "website",
5912
- label: "Personal website",
5913
- // Affirm's "Other Links" is the same free slot for a personal site.
5914
- match: (h) => /^websites?\b/.test(h) || /^other links?$/.test(h),
5915
- sensitive: false
5916
- },
5917
- { id: "github", label: "GitHub profile", match: (h) => /\bgithub\b/.test(h), sensitive: false },
5918
- {
5919
- id: "pronouns",
5920
- label: "Pronouns",
5921
- // Not a question that also asks for a name — Samsara's "share your
5922
- // preferred name and pronouns" wants both in one box, and a bare
5923
- // "He/Him" would answer half of it.
5924
- match: (h) => /\bpronouns?\b/.test(h) && !/\bname\b/.test(h),
5925
- sensitive: false
5926
- }
5927
- ];
5928
- function head(question) {
5929
- return questionKey(question.split("?")[0] ?? "") || questionKey(question);
5930
- }
5931
- function questionFamily(question) {
5932
- const full = questionKey(question);
5933
- if (!full || LEGAL.test(full) || CONDITIONAL.test(full)) return null;
5934
- const h = head(question);
5935
- for (const rule of RULES) {
5936
- if (!rule.match(h)) continue;
5937
- if (rule.sensitive && (FOREIGN.test(h) || questionNegated(questionTerms(h)))) return null;
5938
- return { id: rule.id, label: rule.label };
5939
- }
5940
- return null;
5941
- }
5942
- const US_NAMES = /* @__PURE__ */ new Set([
5943
- "us",
5944
- "u s",
5945
- "usa",
5946
- "u s a",
5947
- "america",
5948
- "united states",
5949
- "united states of america",
5950
- "the united states",
5951
- "the united states of america"
5952
- ]);
5953
- function matchOption(answer, options) {
5954
- const a = answer.trim();
5955
- if (!a) return null;
5956
- if (options.length === 0) return a;
5957
- const na = questionKey(a);
5958
- const exact = options.filter((o) => questionKey(o) === na);
5959
- if (exact.length === 1) return exact[0] ?? null;
5960
- if (US_NAMES.has(na)) {
5961
- const us = options.filter((o) => US_NAMES.has(questionKey(o).replace(/( [0-9]+)+$/, "")));
5962
- if (us.length === 1) return us[0] ?? null;
5963
- }
5964
- const lead = na.split(" ")[0];
5965
- if (lead === "yes" || lead === "no") {
5966
- const same = options.filter((o) => questionKey(o).split(" ")[0] === lead);
5967
- return same.length === 1 ? same[0] ?? null : null;
5576
+ function parseEvidence(raw) {
5577
+ if (raw === null) return null;
5578
+ try {
5579
+ const parsed = JSON.parse(raw);
5580
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
5581
+ } catch {
5582
+ return null;
5968
5583
  }
5969
- const within = (hay, needle) => ` ${hay} `.includes(` ${needle} `);
5970
- const hits = options.filter((o) => {
5971
- const no = questionKey(o);
5972
- return within(no, na) || within(na, no);
5973
- });
5974
- return hits.length === 1 ? hits[0] ?? null : null;
5975
5584
  }
5976
- const MIN_SHARED_TERMS = 2;
5977
- const MAX_SIMILAR = 4;
5978
- function familyFields(question, options, familyAnswers, saved) {
5979
- const fam = questionFamily(question);
5980
- const prior = fam ? familyAnswers.get(fam.id) ?? [] : [];
5981
- const basis = saved ?? prior[0] ?? null;
5585
+ function toApplication(row) {
5982
5586
  return {
5983
- family: fam?.id ?? null,
5984
- family_label: fam?.label ?? null,
5985
- family_answers: prior,
5986
- suggested: basis ? matchOption(basis, options) : null
5587
+ id: row.id,
5588
+ job_id: row.job_id,
5589
+ variant_slug: row.variant_slug,
5590
+ mode: row.mode,
5591
+ status: row.status,
5592
+ error: row.error,
5593
+ evidence: parseEvidence(row.evidence),
5594
+ approved_fingerprint: row.approved_fingerprint,
5595
+ created_at: row.created_at,
5596
+ updated_at: row.updated_at
5987
5597
  };
5988
5598
  }
5989
- function findSimilar(pendingKey, pendingQuestion, answered) {
5990
- const pendingTerms = questionTerms(pendingKey);
5991
- if (pendingTerms.size === 0) return [];
5992
- const pendingNeg = questionNegated(pendingTerms);
5993
- const pendingFam = questionFamily(pendingQuestion)?.id ?? null;
5994
- const scored = [];
5995
- for (const a of answered) {
5996
- const terms = questionTerms(a.question_key);
5997
- if (terms.size === 0) continue;
5998
- if ((questionFamily(a.question)?.id ?? null) !== pendingFam && questionNegated(terms) === pendingNeg) {
5999
- continue;
5599
+ function reconcile(evidence, stored) {
5600
+ const out = { answered_since: [], still_unanswered: [], overridden: [] };
5601
+ if (!evidence) return out;
5602
+ const unmatched = Array.isArray(evidence.unmatched) ? evidence.unmatched : [];
5603
+ for (const raw of unmatched) {
5604
+ if (typeof raw !== "string" || !raw.trim()) continue;
5605
+ const hit = stored.get(questionKey(raw));
5606
+ if (hit) out.answered_since.push({ question: raw, answer: hit.answer });
5607
+ else out.still_unanswered.push(raw);
5608
+ }
5609
+ const answers = evidence.answers;
5610
+ if (typeof answers === "object" && answers !== null && !Array.isArray(answers)) {
5611
+ for (const [key, filled] of Object.entries(answers)) {
5612
+ if (typeof filled !== "string") continue;
5613
+ const hit = stored.get(key);
5614
+ if (hit && hit.answer !== filled) {
5615
+ out.overridden.push({ question: hit.question, filled, stored: hit.answer });
5616
+ }
6000
5617
  }
6001
- const shared = [...pendingTerms].filter((t) => terms.has(t));
6002
- if (shared.length < MIN_SHARED_TERMS) continue;
6003
- const onlyPending = [...pendingTerms].filter((t) => !terms.has(t));
6004
- const onlyAnswered = [...terms].filter((t) => !pendingTerms.has(t));
6005
- const answeredNeg = questionNegated(terms);
6006
- scored.push({
6007
- question_key: a.question_key,
6008
- question: a.question,
6009
- answer: a.answer,
6010
- shared_terms: shared.sort(),
6011
- only_in_pending: onlyPending.sort(),
6012
- only_in_answered: onlyAnswered.sort(),
6013
- polarity_differs: pendingNeg !== answeredNeg,
6014
- // The runner's own rule, reported rather than acted on: every
6015
- // meaningful word of the pending question is already in the stored
6016
- // one, and polarity agrees.
6017
- runner_would_match: pendingTerms.size >= 2 && onlyPending.length === 0 && pendingNeg === answeredNeg,
6018
- // Jaccard: rewards overlap but penalises each side's leftovers, so a
6019
- // short generic question does not top the list against everything.
6020
- score: shared.length / (pendingTerms.size + terms.size - shared.length)
6021
- });
6022
5618
  }
6023
- return scored.sort((a, b) => b.score - a.score).slice(0, MAX_SIMILAR).map(({ score: _score, ...rest }) => rest);
5619
+ return out;
6024
5620
  }
6025
- async function unansweredQuestions(db, userId) {
6026
- const rows = await db.prepare(
6027
- `SELECT a.evidence, a.status, a.updated_at, j.company
6028
- FROM applications a
6029
- JOIN jobs j ON j.id = a.job_id
6030
- WHERE a.user_id = ? AND a.evidence IS NOT NULL`
6031
- ).bind(userId).all();
6032
- const answered = await db.prepare(
6033
- `SELECT question_key, question, answer, updated_at FROM application_answers
6034
- WHERE user_id = ? ORDER BY updated_at DESC`
6035
- ).bind(userId).all();
6036
- const known = new Set(answered.results.map((r) => r.question_key));
6037
- const savedAnswer = new Map(answered.results.map((r) => [r.question_key, r.answer]));
6038
- const savedAt = new Map(answered.results.map((r) => [r.question_key, r.updated_at]));
6039
- const familyAnswers = /* @__PURE__ */ new Map();
6040
- for (const a of answered.results) {
6041
- const fam = questionFamily(a.question);
6042
- if (!fam || !a.answer.trim()) continue;
6043
- const list = familyAnswers.get(fam.id) ?? [];
6044
- if (!list.some((x) => x.toLowerCase() === a.answer.trim().toLowerCase()))
6045
- list.push(a.answer.trim());
6046
- familyAnswers.set(fam.id, list);
6047
- }
6048
- const learnedOptions = /* @__PURE__ */ new Map();
6049
- const pending = /* @__PURE__ */ new Map();
6050
- const learnedMulti = /* @__PURE__ */ new Set();
6051
- for (const row of rows.results) {
6052
- let unmatched;
6053
- let blockingKeys = null;
6054
- let optionsByKey = {};
6055
- try {
6056
- const parsedEvidence = JSON.parse(row.evidence);
6057
- unmatched = parsedEvidence.unmatched;
6058
- if (Array.isArray(parsedEvidence.blocking)) {
6059
- blockingKeys = new Set(
6060
- parsedEvidence.blocking.filter((b) => typeof b === "string").map((b) => questionKey(b))
6061
- );
6062
- }
6063
- const opts = parsedEvidence.options;
6064
- if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) {
6065
- optionsByKey = opts;
6066
- }
6067
- if (Array.isArray(parsedEvidence.multi)) {
6068
- for (const k of parsedEvidence.multi) {
6069
- if (typeof k === "string" && k) learnedMulti.add(questionKey(k));
6070
- }
6071
- }
6072
- } catch {
6073
- continue;
6074
- }
6075
- for (const [key, seen] of Object.entries(optionsByKey)) {
6076
- if (learnedOptions.has(key) || !Array.isArray(seen)) continue;
6077
- const clean = seen.filter((o) => typeof o === "string" && !!o);
6078
- if (clean.length) learnedOptions.set(key, clean);
6079
- }
6080
- if (!Array.isArray(unmatched)) continue;
6081
- for (const raw of unmatched) {
6082
- if (typeof raw !== "string" || !raw.trim()) continue;
6083
- const key = questionKey(raw);
6084
- if (!key) continue;
6085
- const rejected = known.has(key) && row.status === "needs_manual" && blockingKeys !== null && blockingKeys.has(key) && (savedAt.get(key) ?? "") <= row.updated_at;
6086
- if (known.has(key) && !rejected) continue;
6087
- const entry = pending.get(key) ?? {
6088
- question: raw.trim(),
6089
- companies: /* @__PURE__ */ new Set(),
6090
- applications: 0,
6091
- blocking: 0,
6092
- options: [],
6093
- optionsFromBlocker: false,
6094
- savedAnswer: rejected ? savedAnswer.get(key) ?? null : null
6095
- };
6096
- const seenHere = optionsByKey[key];
6097
- const own = Array.isArray(seenHere) ? seenHere.filter((o) => typeof o === "string" && !!o) : [];
6098
- const blocksHere = row.status === "needs_manual" && (blockingKeys === null || blockingKeys.has(key));
6099
- if (blocksHere && own.length && !entry.optionsFromBlocker) {
6100
- entry.options = own;
6101
- entry.optionsFromBlocker = true;
6102
- } else if (!entry.options.length) {
6103
- entry.options = own.length ? own : learnedOptions.get(key) ?? [];
6104
- }
6105
- entry.companies.add(row.company);
6106
- entry.applications += 1;
6107
- if (row.status === "needs_manual" && (blockingKeys === null || blockingKeys.has(key))) {
6108
- entry.blocking += 1;
6109
- }
6110
- pending.set(key, entry);
6111
- }
6112
- }
6113
- for (const { question } of COMMON_QUESTIONS) {
6114
- const key = questionKey(question);
6115
- if (!key || known.has(key) || pending.has(key)) continue;
6116
- pending.set(key, {
6117
- question,
6118
- companies: /* @__PURE__ */ new Set(),
6119
- applications: 0,
6120
- blocking: 0,
6121
- // A seed carries no company, but it may still have options: a fill
6122
- // that ANSWERED this question still learnt what it accepts. That is
6123
- // the whole reason `learnedOptions` is built separately.
6124
- options: learnedOptions.get(key) ?? [],
6125
- optionsFromBlocker: false,
6126
- savedAnswer: null
6127
- });
6128
- }
6129
- return [...pending.entries()].filter(([, v]) => v.blocking > 0 || !isFollowUp(v.question)).map(([key, v]) => ({
6130
- question_key: key,
6131
- question: v.question,
6132
- companies: [...v.companies].sort(),
6133
- applications: v.applications,
6134
- options: v.options,
6135
- multi: learnedMulti.has(key),
6136
- blocking: v.blocking,
6137
- // Every pending question is returned whether or not it looks like a
6138
- // duplicate — the owner asked to see them all. This only annotates.
6139
- similar: findSimilar(key, v.question, answered.results),
6140
- ...familyFields(v.question, v.options, familyAnswers, v.savedAnswer),
6141
- saved_answer: v.savedAnswer
6142
- })).sort((a, b) => b.blocking - a.blocking || b.applications - a.applications);
5621
+ async function delistedReason(db, jobId) {
5622
+ const job = await db.prepare("SELECT ats, slug, last_seen_at FROM jobs WHERE id = ?").bind(jobId).first();
5623
+ if (!job?.ats || !job.slug || !job.last_seen_at) return null;
5624
+ const newest = (await boardNewest(db, [job])).values().next().value ?? null;
5625
+ if (!isDelisted(job.last_seen_at, newest)) return null;
5626
+ return `this posting has not appeared in a scrape of the ${job.ats} board '${job.slug}' since ${job.last_seen_at}, while other jobs on that board were seen as recently as ${newest} — it looks taken down`;
6143
5627
  }
6144
- function registerAnswerRoutes(app2) {
6145
- app2.get("/application-answers", gateAuthed);
6146
- app2.put("/application-answers", gateAuthed);
6147
- app2.delete("/application-answers/:key", gateAuthed);
6148
- app2.get("/unanswered-questions", gateAuthed);
5628
+ const FORBIDDEN = {
5629
+ success: false,
5630
+ error: "Forbidden",
5631
+ message: "Authentication required"
5632
+ };
5633
+ function registerApplicationRoutes(app2) {
5634
+ app2.post("/jobs/:id/apply", gateAuthed);
5635
+ app2.get("/applications", gateAuthed);
5636
+ app2.post("/applications/:id/status", gateAuthed);
5637
+ app2.post("/applications/:id/approve", gateAuthed);
6149
5638
  app2.openapi(
6150
5639
  createRoute({
6151
- method: "get",
6152
- path: "/application-answers",
6153
- tags: ["Answers"],
6154
- summary: "The caller's standing answers to application questions",
5640
+ method: "post",
5641
+ path: "/jobs/{id}/apply",
5642
+ tags: ["Applications"],
5643
+ summary: "Queue this job for the form runner (the packet is minted at fill, not here)",
6155
5644
  request: {
6156
- query: ownerNameQuery
5645
+ params: z.object({ id: z.string() }),
5646
+ query: ownerNameQuery,
5647
+ body: {
5648
+ content: { "application/json": { schema: ApplyRequestSchema } },
5649
+ required: false
5650
+ }
6157
5651
  },
6158
5652
  responses: {
6159
5653
  200: {
6160
- description: "Answers, most recently updated first",
6161
- content: { "application/json": { schema: AnswersResponseSchema } }
5654
+ description: "Application queued",
5655
+ content: { "application/json": { schema: ApplicationResponseSchema } }
6162
5656
  },
6163
5657
  403: {
6164
5658
  description: "Forbidden",
6165
5659
  content: { "application/json": { schema: ErrorResponseSchema } }
6166
5660
  },
6167
5661
  404: {
6168
- description: "No such owner name",
6169
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6170
- },
6171
- 409: {
6172
- description: "That owner name has never signed in",
6173
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6174
- },
6175
- 503: {
6176
- description: "Identity could not be resolved right now — retry",
6177
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6178
- }
6179
- }
6180
- }),
6181
- async (c) => {
6182
- const { ownerName } = c.req.valid("query");
6183
- const who = await effectiveUserId(c, ownerName);
6184
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6185
- const userId = who.userId;
6186
- const rows = await c.env.JOB_PLATFORM_DB.prepare(
6187
- `SELECT question_key, question, answer, updated_at
6188
- FROM application_answers WHERE user_id = ? ORDER BY updated_at DESC`
6189
- ).bind(userId).all();
6190
- return c.json({ success: true, data: { answers: rows.results } }, 200);
6191
- }
6192
- );
6193
- app2.openapi(
6194
- createRoute({
6195
- method: "put",
6196
- path: "/application-answers",
6197
- tags: ["Answers"],
6198
- summary: "Save (or replace) the answer to one question",
6199
- request: {
6200
- query: ownerNameQuery,
6201
- body: { content: { "application/json": { schema: SetAnswerSchema } } }
6202
- },
6203
- responses: {
6204
- 200: {
6205
- description: "Saved",
6206
- content: { "application/json": { schema: AnswerResponseSchema } }
6207
- },
6208
- 400: {
6209
- description: "Empty question",
5662
+ description: "Job not found",
6210
5663
  content: { "application/json": { schema: ErrorResponseSchema } }
6211
5664
  },
6212
- 403: {
6213
- description: "Forbidden",
5665
+ 422: {
5666
+ description: "The posting was typed in by hand with no link",
6214
5667
  content: { "application/json": { schema: ErrorResponseSchema } }
6215
5668
  },
6216
- 404: {
6217
- description: "No such owner name",
6218
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6219
- },
6220
5669
  409: {
6221
- description: "That owner name has never signed in",
5670
+ description: "The posting looks taken down (retry with force), the row is approved (retry with force) or already submitted, or the owner name has never signed in",
6222
5671
  content: { "application/json": { schema: IdentityErrorResponseSchema } }
6223
5672
  },
6224
5673
  503: {
@@ -6228,484 +5677,1304 @@ function registerAnswerRoutes(app2) {
6228
5677
  }
6229
5678
  }),
6230
5679
  async (c) => {
6231
- const { question, answer, ownerName } = c.req.valid("json");
6232
- const who = await effectiveUserId(c, ownerName);
5680
+ const { id } = c.req.valid("param");
5681
+ const body = c.req.valid("json");
5682
+ const mode = body?.mode ?? "review";
5683
+ const who = await effectiveUserId(c, body?.ownerName);
6233
5684
  if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6234
5685
  const userId = who.userId;
6235
- const key = questionKey(question);
6236
- if (!key) {
5686
+ const db = c.env.JOB_PLATFORM_DB;
5687
+ const job = await db.prepare("SELECT id, url FROM jobs WHERE id = ?").bind(id).first();
5688
+ if (!job) {
5689
+ return c.json(
5690
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
5691
+ 404
5692
+ );
5693
+ }
5694
+ const refuse = (reason) => recordEvent(c, {
5695
+ level: "warn",
5696
+ event: "application.queue_refused",
5697
+ message: `${id}: ${reason}`,
5698
+ context: { job_id: id, user_id: userId, reason }
5699
+ });
5700
+ if (publicUrl(job.url) === null) {
5701
+ refuse("no link");
6237
5702
  return c.json(
6238
5703
  {
6239
5704
  success: false,
6240
- error: "Bad request",
6241
- message: "That question has no matchable text"
5705
+ error: "Unprocessable",
5706
+ message: "This posting has no link, so the runner has no form to fill."
6242
5707
  },
6243
- 400
5708
+ 422
5709
+ );
5710
+ }
5711
+ if (!body?.force) {
5712
+ const delisted = await delistedReason(db, id);
5713
+ if (delisted) {
5714
+ refuse(`delisted: ${delisted}`);
5715
+ return c.json(
5716
+ {
5717
+ success: false,
5718
+ error: "Conflict",
5719
+ message: `${delisted}. Re-apply with {"force": true} if it is still open.`
5720
+ },
5721
+ 409
5722
+ );
5723
+ }
5724
+ }
5725
+ const state = await db.prepare("SELECT variant_slug FROM job_states WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
5726
+ const variantSlug = state?.variant_slug ?? "";
5727
+ const existing = await db.prepare("SELECT status FROM applications WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
5728
+ if (existing?.status === "submitted" || existing?.status === "approved" && !body?.force) {
5729
+ refuse(`already ${existing.status}`);
5730
+ return c.json(
5731
+ {
5732
+ success: false,
5733
+ error: "Conflict",
5734
+ message: existing.status === "submitted" ? "This application was already submitted." : 'This application is approved; re-queueing would discard the approval. Re-apply with {"force": true} to fill it again.'
5735
+ },
5736
+ 409
6244
5737
  );
6245
5738
  }
6246
5739
  const now = (/* @__PURE__ */ new Date()).toISOString();
6247
- await c.env.JOB_PLATFORM_DB.prepare(
6248
- `INSERT INTO application_answers
6249
- (user_id, question_key, question, answer, created_at, updated_at)
6250
- VALUES (?, ?, ?, ?, ?, ?)
6251
- ON CONFLICT (user_id, question_key) DO UPDATE SET
6252
- question = excluded.question,
6253
- answer = excluded.answer,
6254
- updated_at = excluded.updated_at`
6255
- ).bind(userId, key, question.trim(), answer, now, now).run();
5740
+ await db.prepare(
5741
+ `INSERT INTO applications
5742
+ (id, user_id, job_id, variant_slug, mode, status, error, evidence, created_at, updated_at)
5743
+ VALUES (?, ?, ?, ?, ?, 'queued', NULL, NULL, ?, ?)
5744
+ ON CONFLICT (user_id, job_id) DO UPDATE SET
5745
+ -- An empty slug means "not minted yet" and must never overwrite a
5746
+ -- real pin: re-queueing a row whose packet already exists has to
5747
+ -- keep pointing at that packet. Same shape as the COALESCE on
5748
+ -- job_states.variant_slug, for the same reason.
5749
+ variant_slug = COALESCE(NULLIF(excluded.variant_slug, ''), applications.variant_slug),
5750
+ mode = excluded.mode,
5751
+ status = 'queued',
5752
+ error = NULL,
5753
+ evidence = NULL,
5754
+ approved_fingerprint = NULL,
5755
+ updated_at = excluded.updated_at`
5756
+ ).bind(crypto.randomUUID(), userId, id, variantSlug, mode, now, now).run();
5757
+ const row = await db.prepare("SELECT * FROM applications WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
5758
+ if (!row) throw new Error(`application row missing after upsert (job '${id}')`);
5759
+ recordEvent(c, {
5760
+ level: "info",
5761
+ event: "application.queued",
5762
+ message: `${id}: ${existing ? `re-queued from ${existing.status}` : "queued"} (${mode})`,
5763
+ context: {
5764
+ job_id: id,
5765
+ application_id: row.id,
5766
+ user_id: userId,
5767
+ mode,
5768
+ force: Boolean(body?.force),
5769
+ previous: existing?.status ?? null,
5770
+ on_behalf: who.onBehalfOf ?? null
5771
+ }
5772
+ });
5773
+ return c.json({ success: true, data: { application: toApplication(row) } }, 200);
5774
+ }
5775
+ );
5776
+ app2.openapi(
5777
+ createRoute({
5778
+ method: "get",
5779
+ path: "/applications",
5780
+ tags: ["Applications"],
5781
+ summary: "List the caller's queued applications, newest first",
5782
+ request: {
5783
+ query: ownerNameQuery.extend({ status: ApplicationStatusSchema.optional() })
5784
+ },
5785
+ responses: {
5786
+ 200: {
5787
+ description: "Applications, newest first",
5788
+ content: { "application/json": { schema: ApplicationsResponseSchema } }
5789
+ },
5790
+ 403: {
5791
+ description: "Forbidden",
5792
+ content: { "application/json": { schema: ErrorResponseSchema } }
5793
+ },
5794
+ 404: {
5795
+ description: "No such owner name",
5796
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5797
+ },
5798
+ 409: {
5799
+ description: "That owner name has never signed in",
5800
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5801
+ },
5802
+ 503: {
5803
+ description: "Identity could not be resolved right now — retry",
5804
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5805
+ }
5806
+ }
5807
+ }),
5808
+ async (c) => {
5809
+ const { status, ownerName } = c.req.valid("query");
5810
+ startTime(c, "who");
5811
+ const who = await effectiveUserId(c, ownerName);
5812
+ endTime(c, "who");
5813
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
5814
+ const userId = who.userId;
5815
+ const filter = status ? " AND a.status = ?" : "";
5816
+ const stmt = c.env.JOB_PLATFORM_DB.prepare(
5817
+ `SELECT a.id, a.job_id, a.variant_slug, a.mode, a.status, a.error,
5818
+ a.evidence, a.approved_fingerprint, a.created_at, a.updated_at,
5819
+ j.title, j.company, j.location, j.ats, j.slug, j.url
5820
+ FROM applications a
5821
+ INNER JOIN jobs j ON j.id = a.job_id
5822
+ WHERE a.user_id = ?${filter}
5823
+ ORDER BY a.updated_at DESC`
5824
+ );
5825
+ startTime(c, "read");
5826
+ const [rows, answerRows] = await c.env.JOB_PLATFORM_DB.batch([
5827
+ status ? stmt.bind(userId, status) : stmt.bind(userId),
5828
+ c.env.JOB_PLATFORM_DB.prepare(
5829
+ "SELECT question_key, question, answer FROM application_answers WHERE user_id = ?"
5830
+ ).bind(userId)
5831
+ ]);
5832
+ endTime(c, "read");
5833
+ const appRows = rows.results;
5834
+ const answers = answerRows.results;
5835
+ const stored = new Map(
5836
+ answers.map((a) => [a.question_key, { question: a.question, answer: a.answer }])
5837
+ );
5838
+ const applications = appRows.map((r) => {
5839
+ const app22 = toApplication(r);
5840
+ return {
5841
+ ...app22,
5842
+ title: r.title,
5843
+ company: r.company,
5844
+ location: r.location,
5845
+ form_url: formUrl({ id: r.job_id, ats: r.ats, slug: r.slug, url: r.url }),
5846
+ ...reconcile(app22.evidence, stored)
5847
+ };
5848
+ });
5849
+ return c.json(
5850
+ {
5851
+ success: true,
5852
+ data: { applications, owner: { userId, name: who.onBehalfOf } }
5853
+ },
5854
+ 200
5855
+ );
5856
+ }
5857
+ );
5858
+ app2.openapi(
5859
+ createRoute({
5860
+ method: "post",
5861
+ path: "/applications/{id}/status",
5862
+ tags: ["Applications"],
5863
+ summary: "Record a status transition (runner endpoint; loose for v1)",
5864
+ request: {
5865
+ params: z.object({ id: z.string() }),
5866
+ query: ownerNameQuery,
5867
+ body: { content: { "application/json": { schema: SetApplicationStatusSchema } } }
5868
+ },
5869
+ responses: {
5870
+ 200: {
5871
+ description: "Status recorded",
5872
+ content: { "application/json": { schema: ApplicationResponseSchema } }
5873
+ },
5874
+ 403: {
5875
+ description: "Forbidden",
5876
+ content: { "application/json": { schema: ErrorResponseSchema } }
5877
+ },
5878
+ 404: {
5879
+ description: "Application not found, or no such owner name",
5880
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5881
+ },
5882
+ 409: {
5883
+ description: "That owner name has never signed in",
5884
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5885
+ },
5886
+ 503: {
5887
+ description: "Identity could not be resolved right now — retry",
5888
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
5889
+ }
5890
+ }
5891
+ }),
5892
+ async (c) => {
5893
+ const { id } = c.req.valid("param");
5894
+ const body = c.req.valid("json");
5895
+ const who = await effectiveUserId(c, body.ownerName);
5896
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
5897
+ const userId = who.userId;
5898
+ const db = c.env.JOB_PLATFORM_DB;
5899
+ const existing = await db.prepare("SELECT * FROM applications WHERE id = ? AND user_id = ?").bind(id, userId).first();
5900
+ if (!existing) {
5901
+ recordEvent(c, {
5902
+ level: "warn",
5903
+ event: "application.status_unknown",
5904
+ message: `${id}: ${body.status} for an application not found`,
5905
+ context: {
5906
+ application_id: id,
5907
+ user_id: userId,
5908
+ status: body.status,
5909
+ error: body.error ?? null
5910
+ }
5911
+ });
5912
+ return c.json(
5913
+ {
5914
+ success: false,
5915
+ error: "Not found",
5916
+ message: `Application '${id}' not found`
5917
+ },
5918
+ 404
5919
+ );
5920
+ }
5921
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5922
+ const evidence = body.evidence !== void 0 ? JSON.stringify(body.evidence) : existing.evidence;
5923
+ const approvedFingerprint = body.status === "submitted" ? existing.approved_fingerprint : null;
5924
+ await db.prepare(
5925
+ `UPDATE applications SET status = ?, error = ?, evidence = ?,
5926
+ approved_fingerprint = ?, updated_at = ?
5927
+ WHERE id = ?`
5928
+ ).bind(body.status, body.error ?? null, evidence, approvedFingerprint, now, id).run();
5929
+ recordEvent(c, {
5930
+ level: body.status === "failed" ? "warn" : "info",
5931
+ event: "application.status",
5932
+ message: `${id}: ${existing.status} -> ${body.status}${body.error ? ` (${body.error.slice(0, 120)})` : ""}`,
5933
+ context: {
5934
+ application_id: id,
5935
+ job_id: existing.job_id,
5936
+ user_id: userId,
5937
+ from: existing.status,
5938
+ to: body.status,
5939
+ error: body.error ?? null,
5940
+ on_behalf: who.onBehalfOf ?? null
5941
+ }
5942
+ });
6256
5943
  return c.json(
6257
5944
  {
6258
5945
  success: true,
6259
5946
  data: {
6260
- answer: {
6261
- question_key: key,
6262
- question: question.trim(),
6263
- answer,
5947
+ application: toApplication({
5948
+ ...existing,
5949
+ status: body.status,
5950
+ error: body.error ?? null,
5951
+ evidence,
5952
+ approved_fingerprint: approvedFingerprint,
6264
5953
  updated_at: now
6265
- }
5954
+ })
6266
5955
  }
6267
5956
  },
6268
- 200
5957
+ 200
5958
+ );
5959
+ }
5960
+ );
5961
+ app2.openapi(
5962
+ createRoute({
5963
+ method: "post",
5964
+ path: "/applications/{id}/approve",
5965
+ tags: ["Applications"],
5966
+ summary: "Approve a filled application for submission (review-mode pause point)",
5967
+ request: { params: z.object({ id: z.string() }) },
5968
+ responses: {
5969
+ 200: {
5970
+ description: "Approved — the runner will submit",
5971
+ content: { "application/json": { schema: ApplicationResponseSchema } }
5972
+ },
5973
+ 403: {
5974
+ description: "Forbidden",
5975
+ content: { "application/json": { schema: ErrorResponseSchema } }
5976
+ },
5977
+ 404: {
5978
+ description: "Application not found",
5979
+ content: { "application/json": { schema: ErrorResponseSchema } }
5980
+ },
5981
+ 409: {
5982
+ description: "Not in 'filled', or filled without a fingerprint to bind to",
5983
+ content: { "application/json": { schema: ErrorResponseSchema } }
5984
+ }
5985
+ }
5986
+ }),
5987
+ async (c) => {
5988
+ const userId = await maybeUserId(c);
5989
+ if (!userId) return c.json(FORBIDDEN, 403);
5990
+ const { id } = c.req.valid("param");
5991
+ const db = c.env.JOB_PLATFORM_DB;
5992
+ const existing = await db.prepare("SELECT * FROM applications WHERE id = ? AND user_id = ?").bind(id, userId).first();
5993
+ if (!existing) {
5994
+ return c.json(
5995
+ {
5996
+ success: false,
5997
+ error: "Not found",
5998
+ message: `Application '${id}' not found`
5999
+ },
6000
+ 404
6001
+ );
6002
+ }
6003
+ if (existing.status !== "filled") {
6004
+ recordEvent(c, {
6005
+ level: "warn",
6006
+ event: "application.approve_refused",
6007
+ message: `${id}: is ${existing.status}, not filled`,
6008
+ context: { application_id: id, user_id: userId, status: existing.status }
6009
+ });
6010
+ return c.json(
6011
+ {
6012
+ success: false,
6013
+ error: "Conflict",
6014
+ message: `Application '${id}' is '${existing.status}', not 'filled' — only a filled application can be approved`
6015
+ },
6016
+ 409
6017
+ );
6018
+ }
6019
+ const fingerprint = parseEvidence(existing.evidence)?.fingerprint;
6020
+ if (typeof fingerprint !== "string" || fingerprint.length === 0) {
6021
+ recordEvent(c, {
6022
+ level: "warn",
6023
+ event: "application.approve_refused",
6024
+ message: `${id}: filled without a fingerprint`,
6025
+ context: { application_id: id, user_id: userId, status: existing.status }
6026
+ });
6027
+ return c.json(
6028
+ {
6029
+ success: false,
6030
+ error: "Conflict",
6031
+ message: `Application '${id}' was filled without a fingerprint, so there is nothing to bind this approval to — re-run the fill and approve the new screenshot`
6032
+ },
6033
+ 409
6034
+ );
6035
+ }
6036
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6037
+ await db.prepare(
6038
+ `UPDATE applications SET status = 'approved', approved_fingerprint = ?,
6039
+ updated_at = ? WHERE id = ?`
6040
+ ).bind(fingerprint, now, id).run();
6041
+ recordEvent(c, {
6042
+ level: "info",
6043
+ event: "application.approved",
6044
+ message: `${id}: approved`,
6045
+ context: { application_id: id, job_id: existing.job_id, user_id: userId }
6046
+ });
6047
+ return c.json(
6048
+ {
6049
+ success: true,
6050
+ data: {
6051
+ application: toApplication({
6052
+ ...existing,
6053
+ status: "approved",
6054
+ approved_fingerprint: fingerprint,
6055
+ updated_at: now
6056
+ })
6057
+ }
6058
+ },
6059
+ 200
6060
+ );
6061
+ }
6062
+ );
6063
+ }
6064
+ function str(v) {
6065
+ return typeof v === "string" ? v.trim() : typeof v === "number" ? String(v) : "";
6066
+ }
6067
+ function records(v) {
6068
+ return Array.isArray(v) ? v.filter((x) => typeof x === "object" && x !== null && !Array.isArray(x)) : [];
6069
+ }
6070
+ function monthYear(month, year) {
6071
+ const y = str(year);
6072
+ if (!y) return "";
6073
+ const m = str(month);
6074
+ return m ? `${m.padStart(2, "0")}/${y}` : y;
6075
+ }
6076
+ function languageLine(v) {
6077
+ if (typeof v === "string") return v.trim();
6078
+ if (!Array.isArray(v)) return "";
6079
+ return v.map((l) => {
6080
+ if (typeof l === "string") return l.trim();
6081
+ if (typeof l !== "object" || l === null) return "";
6082
+ const o = l;
6083
+ const name = str(o.language) || str(o.name);
6084
+ const level = str(o.level) || str(o.proficiency);
6085
+ return name && level ? `${name} (${level})` : name;
6086
+ }).filter(Boolean).join(", ");
6087
+ }
6088
+ function profileResumeText(profile) {
6089
+ const master = str(profile.master_resume_text);
6090
+ if (master) return master;
6091
+ const sections = [];
6092
+ const summary = [str(profile.headline), str(profile.summary)].filter(Boolean).join("\n\n");
6093
+ if (summary) sections.push(`## Summary
6094
+
6095
+ ${summary}`);
6096
+ const jobs = records(profile.work_experience).filter((w) => str(w.company)).map((w) => {
6097
+ const start = monthYear(w.start_month, w.start_year);
6098
+ const end = w.current === true ? "present" : monthYear(w.end_month, w.end_year);
6099
+ const dates = [start, end].filter(Boolean).join(" - ");
6100
+ const title = str(w.title) || str(w.company);
6101
+ const heading = dates ? `${title} - ${dates}` : title;
6102
+ const lines = [`### ${heading}`, `**${str(w.company)}**`];
6103
+ const description = str(w.description) || str(w.summary);
6104
+ if (description) lines.push("", description);
6105
+ return lines.join("\n");
6106
+ });
6107
+ if (jobs.length) sections.push(`## Experience
6108
+
6109
+ ${jobs.join("\n\n")}`);
6110
+ const schools = records(profile.education).filter((e) => str(e.school)).map((e) => {
6111
+ const what = [str(e.degree), str(e.discipline)].filter(Boolean).join(", ");
6112
+ const years = [str(e.start_year), str(e.end_year)].filter(Boolean).join(" - ");
6113
+ return `- ${[what, str(e.school), years].filter(Boolean).join(", ")}`;
6114
+ });
6115
+ if (schools.length) sections.push(`## Education
6116
+
6117
+ ${schools.join("\n")}`);
6118
+ const skills = Array.isArray(profile.skills) ? profile.skills.map(str).filter(Boolean).join(", ") : str(profile.skills);
6119
+ if (skills) sections.push(`## Skills
6120
+
6121
+ ${skills}`);
6122
+ const languages = languageLine(profile.languages);
6123
+ if (languages) sections.push(`## Languages
6124
+
6125
+ ${languages}`);
6126
+ if (!sections.length) return null;
6127
+ const contact = [
6128
+ str(profile.email),
6129
+ str(profile.phone),
6130
+ str(profile.location),
6131
+ str(profile.linkedin)
6132
+ ].filter(Boolean).join(" - ");
6133
+ const header = [`# ${str(profile.name)}`, contact].filter(Boolean).join("\n\n");
6134
+ return `${header}
6135
+
6136
+ ${sections.join("\n\n")}
6137
+ `;
6138
+ }
6139
+ function profileContact(profile) {
6140
+ return {
6141
+ name: str(profile.name),
6142
+ email: str(profile.email),
6143
+ phone: str(profile.phone),
6144
+ linkedin: str(profile.linkedin),
6145
+ github: str(profile.github),
6146
+ location: str(profile.location),
6147
+ work_auth: str(profile.work_authorization),
6148
+ relocation: str(profile.relocation),
6149
+ salary_line: str(profile.desired_salary)
6150
+ };
6151
+ }
6152
+ function resumeViaEdge(env, path, init) {
6153
+ if (!env.EDGE) throw new Error("EDGE service binding not configured");
6154
+ const key = env.HADOKU_SERVICE_KEY?.trim();
6155
+ if (!key) throw new Error("HADOKU_SERVICE_KEY not configured");
6156
+ const headers = new Headers(init.headers);
6157
+ headers.set("X-User-Key", key);
6158
+ return env.EDGE.fetch(`${EDGE_BASE}${path}`, { ...init, headers });
6159
+ }
6160
+ async function callResumeBinding(env, path, payload, method = "POST") {
6161
+ return resumeViaEdge(env, path, {
6162
+ method,
6163
+ headers: { "Content-Type": "application/json" },
6164
+ body: JSON.stringify(payload)
6165
+ });
6166
+ }
6167
+ function resumeNeedsReseed(before, after) {
6168
+ const text = profileResumeText(after);
6169
+ if (!text) return false;
6170
+ if (!before) return true;
6171
+ if (text !== profileResumeText(before)) return true;
6172
+ return JSON.stringify(profileContact(after)) !== JSON.stringify(profileContact(before));
6173
+ }
6174
+ function errorCode(detail) {
6175
+ try {
6176
+ const body = JSON.parse(detail);
6177
+ const code = typeof body === "object" && body !== null ? body.code : null;
6178
+ return typeof code === "string" ? code : null;
6179
+ } catch {
6180
+ return null;
6181
+ }
6182
+ }
6183
+ async function reseedResume(env, userId, profile) {
6184
+ const text = profileResumeText(profile);
6185
+ if (!text) return;
6186
+ const res = await callResumeBinding(env, "/resume/api/blocks/import", {
6187
+ on_behalf_of_user_id: userId,
6188
+ resume_text: text,
6189
+ contact: profileContact(profile),
6190
+ replace: true
6191
+ });
6192
+ if (res.ok) return;
6193
+ const detail = await res.text();
6194
+ if (res.status === 403 && errorCode(detail) === "OWNER_SET") return;
6195
+ if (res.status === 404) {
6196
+ logger.warn("resume-api has no per-user résumé import yet; reseed skipped", {
6197
+ user_id: userId
6198
+ });
6199
+ return;
6200
+ }
6201
+ throw new Error(`resume-api reseed ${res.status}: ${detail.slice(0, 300)}`);
6202
+ }
6203
+ const RESUME_PDF_URL = "https://hadoku.me/resume/api/resume.pdf";
6204
+ function badRequest(message) {
6205
+ return { success: false, error: "Bad request", message };
6206
+ }
6207
+ function validProfile(p) {
6208
+ if (typeof p !== "object" || p === null || Array.isArray(p)) return false;
6209
+ const o = p;
6210
+ return typeof o.name === "string" && !!o.name.trim() && typeof o.email === "string";
6211
+ }
6212
+ const PROFILE_TEXT_LIMITS = {
6213
+ work_authorization: 200,
6214
+ desired_salary: 100,
6215
+ notice_period: 100,
6216
+ master_resume_text: 5e4
6217
+ };
6218
+ function profileProblem(p) {
6219
+ for (const [key, max] of Object.entries(PROFILE_TEXT_LIMITS)) {
6220
+ const v = p[key];
6221
+ if (v === void 0 || v === null) continue;
6222
+ if (typeof v !== "string") return `${key} must be a string`;
6223
+ if (v.length > max) return `${key} is longer than ${max} characters`;
6224
+ }
6225
+ return null;
6226
+ }
6227
+ async function loadProfile(db, userId) {
6228
+ const row = await db.prepare("SELECT profile, updated_at FROM applicant_profiles WHERE user_id = ?").bind(userId).first();
6229
+ if (!row) return null;
6230
+ try {
6231
+ const parsed = JSON.parse(row.profile);
6232
+ return validProfile(parsed) ? { profile: parsed, updated_at: row.updated_at } : null;
6233
+ } catch {
6234
+ return null;
6235
+ }
6236
+ }
6237
+ function registerFillRoutes(app2) {
6238
+ app2.get("/applicant-profile", gateAuthed);
6239
+ app2.get("/applicant-profile", async (c) => {
6240
+ const who = await effectiveUserId(c, c.req.query("ownerName"));
6241
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6242
+ const found = await loadProfile(c.env.JOB_PLATFORM_DB, who.userId);
6243
+ return c.json(
6244
+ {
6245
+ success: true,
6246
+ data: { profile: found?.profile ?? null, updated_at: found?.updated_at ?? null }
6247
+ },
6248
+ 200
6249
+ );
6250
+ });
6251
+ app2.put("/applicant-profile", gateAuthed);
6252
+ app2.put("/applicant-profile", async (c) => {
6253
+ let body;
6254
+ try {
6255
+ body = await c.req.json();
6256
+ } catch {
6257
+ return c.json(badRequest("Body must be JSON"), 400);
6258
+ }
6259
+ const b = typeof body === "object" && body !== null ? body : {};
6260
+ if (!validProfile(b.profile)) {
6261
+ return c.json(badRequest("profile must be an object with a name and an email"), 400);
6262
+ }
6263
+ const problem = profileProblem(b.profile);
6264
+ if (problem) return c.json(badRequest(problem), 400);
6265
+ const who = await effectiveUserId(c, typeof b.ownerName === "string" ? b.ownerName : void 0);
6266
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6267
+ const before = await loadProfile(c.env.JOB_PLATFORM_DB, who.userId);
6268
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6269
+ await c.env.JOB_PLATFORM_DB.prepare(
6270
+ `INSERT INTO applicant_profiles (user_id, profile, updated_at) VALUES (?, ?, ?)
6271
+ ON CONFLICT (user_id) DO UPDATE SET profile = excluded.profile, updated_at = excluded.updated_at`
6272
+ ).bind(who.userId, JSON.stringify(b.profile), now).run();
6273
+ if (resumeNeedsReseed(before?.profile, b.profile)) {
6274
+ runAfterResponse(c, "resume-api reseed", reseedResume(c.env, who.userId, b.profile));
6275
+ }
6276
+ return c.json({ success: true, data: { updated_at: now } }, 200);
6277
+ });
6278
+ app2.get("/jobs/:id/fill-packet", gateAuthed);
6279
+ app2.get("/jobs/:id/fill-packet", async (c) => {
6280
+ const id = c.req.param("id");
6281
+ const who = await effectiveUserId(c, c.req.query("ownerName"));
6282
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6283
+ const db = c.env.JOB_PLATFORM_DB;
6284
+ const job = await db.prepare("SELECT id, company, title, url FROM jobs WHERE id = ?").bind(id).first();
6285
+ if (!job) {
6286
+ return c.json(
6287
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
6288
+ 404
6289
+ );
6290
+ }
6291
+ const app_ = await db.prepare(
6292
+ `SELECT id, status, variant_slug, evidence FROM applications
6293
+ WHERE user_id = ? AND job_id = ?`
6294
+ ).bind(who.userId, id).first();
6295
+ const state = await db.prepare("SELECT variant_slug FROM job_states WHERE user_id = ? AND job_id = ?").bind(who.userId, id).first();
6296
+ const slug2 = app_?.variant_slug || state?.variant_slug || "";
6297
+ const evidence = parseEvidence(app_?.evidence ?? null) ?? {};
6298
+ const answers = typeof evidence.answers === "object" && evidence.answers !== null ? evidence.answers : {};
6299
+ const options = typeof evidence.options === "object" && evidence.options !== null ? evidence.options : {};
6300
+ const multi = Array.isArray(evidence.multi) ? evidence.multi : [];
6301
+ const standing = await db.prepare("SELECT question, answer FROM application_answers WHERE user_id = ?").bind(who.userId).all();
6302
+ const profile = await loadProfile(db, who.userId);
6303
+ return c.json(
6304
+ {
6305
+ success: true,
6306
+ data: {
6307
+ job: { ...job, url: publicUrl(job.url) },
6308
+ application: app_ ? { id: app_.id, status: app_.status, variant_slug: slug2 } : null,
6309
+ profile: profile?.profile ?? null,
6310
+ // What the approved fill entered, keyed by the runner's normalised
6311
+ // question — the primary source, because it is what was reviewed.
6312
+ answers,
6313
+ options,
6314
+ multi,
6315
+ // Every saved answer by its question, for anything the fill did
6316
+ // not record (a field added since, a structured block).
6317
+ standing: Object.fromEntries(standing.results.map((r) => [r.question, r.answer])),
6318
+ resume_pdf_url: slug2 ? `${RESUME_PDF_URL}?v=${encodeURIComponent(slug2)}` : null
6319
+ }
6320
+ },
6321
+ 200
6322
+ );
6323
+ });
6324
+ }
6325
+ async function loadTailoringFields(db, id) {
6326
+ return db.prepare("SELECT title, company, description, location, workplace_type FROM jobs WHERE id = ?").bind(id).first();
6327
+ }
6328
+ async function missingContent(res) {
6329
+ if (res.status !== 409) return null;
6330
+ try {
6331
+ const body = await res.clone().json();
6332
+ return body.code === "NO_RESUME_BLOCKS" || body.code === "NO_CONTACT_PROFILE" ? body.code : null;
6333
+ } catch {
6334
+ return null;
6335
+ }
6336
+ }
6337
+ const MISSING_CONTENT_MESSAGE = {
6338
+ NO_RESUME_BLOCKS: "Your résumé is not set up yet. Paste it into the Résumé box on the Profile page (or fill in your work history there), then try again. Tailored résumés and cover letters are built only from your own résumé.",
6339
+ NO_CONTACT_PROFILE: "Your contact details are not set up yet. Fill in your applicant profile (Profile page), then try again."
6340
+ };
6341
+ async function callResumeFor(c, userId, path, payload) {
6342
+ const body = { ...payload, on_behalf_of_user_id: userId };
6343
+ const first = await callResumeBinding(c.env, path, body);
6344
+ const missing = await missingContent(first);
6345
+ if (!missing) return { res: first };
6346
+ const profile = (await loadProfile(c.env.JOB_PLATFORM_DB, userId))?.profile;
6347
+ if (!profile) return { refusal: missing };
6348
+ if (missing === "NO_RESUME_BLOCKS") {
6349
+ const text = profileResumeText(profile);
6350
+ if (!text) return { refusal: missing };
6351
+ const seeded = await callResumeBinding(c.env, "/resume/api/blocks/import", {
6352
+ on_behalf_of_user_id: userId,
6353
+ resume_text: text,
6354
+ contact: profileContact(profile)
6355
+ });
6356
+ if (!seeded.ok && seeded.status !== 409) return { res: seeded };
6357
+ } else {
6358
+ const put = await callResumeBinding(
6359
+ c.env,
6360
+ "/resume/api/contact-profile",
6361
+ { on_behalf_of_user_id: userId, contact: profileContact(profile) },
6362
+ "PUT"
6363
+ );
6364
+ if (!put.ok) return { res: put };
6365
+ }
6366
+ recordEvent(c, {
6367
+ level: "info",
6368
+ event: "tailoring.seeded",
6369
+ message: `seeded resume-api ${missing === "NO_RESUME_BLOCKS" ? "blocks" : "contact"} from the applicant profile`,
6370
+ context: { user_id: userId, missing }
6371
+ });
6372
+ const retry = await callResumeBinding(c.env, path, body);
6373
+ const still = await missingContent(retry);
6374
+ return still ? { refusal: still } : { res: retry };
6375
+ }
6376
+ function refusalBody(missing) {
6377
+ return {
6378
+ success: false,
6379
+ error: "Résumé not set up",
6380
+ code: missing,
6381
+ message: MISSING_CONTENT_MESSAGE[missing]
6382
+ };
6383
+ }
6384
+ async function fetchMintedResume(env, slug2) {
6385
+ const res = await resumeViaEdge(env, `/resume/api/resume?v=${encodeURIComponent(slug2)}`, {
6386
+ method: "GET"
6387
+ });
6388
+ if (!res.ok) return { expired: true };
6389
+ const body = await res.json();
6390
+ if (!body.variant || !body.content) return { expired: true };
6391
+ return { markdown: body.content };
6392
+ }
6393
+ async function readOptions(c) {
6394
+ try {
6395
+ const body = await c.req.json();
6396
+ return typeof body === "object" && body !== null && !Array.isArray(body) ? body : {};
6397
+ } catch {
6398
+ return {};
6399
+ }
6400
+ }
6401
+ function ownerNameOf(opts) {
6402
+ return typeof opts.ownerName === "string" ? opts.ownerName : void 0;
6403
+ }
6404
+ function questionsOf(opts) {
6405
+ if (!Array.isArray(opts.questions)) return void 0;
6406
+ const questions = opts.questions.filter((q) => typeof q === "string" && q.trim() !== "").map((q) => q.trim().slice(0, 500)).slice(0, 25);
6407
+ return questions.length ? questions : void 0;
6408
+ }
6409
+ const UPSTREAM_DETAIL_CHARS = 1500;
6410
+ async function upstreamError(c, kind, jobId, res) {
6411
+ const detail = (await res.text()).slice(0, UPSTREAM_DETAIL_CHARS);
6412
+ recordEvent(c, {
6413
+ level: "warn",
6414
+ event: "tailoring.failed",
6415
+ message: `${kind} for ${jobId}: resume-api ${res.status}`,
6416
+ context: { kind, job_id: jobId, upstream_status: res.status, detail }
6417
+ });
6418
+ return {
6419
+ success: false,
6420
+ error: "Upstream error",
6421
+ message: `resume-api ${res.status}: ${detail}`
6422
+ };
6423
+ }
6424
+ function generated(c, kind, jobId, extra = {}) {
6425
+ recordEvent(c, {
6426
+ level: "info",
6427
+ event: "tailoring.generated",
6428
+ message: `${kind} for ${jobId}`,
6429
+ context: { kind, job_id: jobId, ...extra }
6430
+ });
6431
+ }
6432
+ function registerTailoringRoutes(app2) {
6433
+ app2.post("/jobs/:id/resume", gateAuthed);
6434
+ app2.post("/jobs/:id/cover-letter", gateAuthed);
6435
+ app2.post("/jobs/:id/resume", async (c) => {
6436
+ const id = c.req.param("id");
6437
+ const opts = await readOptions(c);
6438
+ const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
6439
+ if (!job) {
6440
+ return c.json(
6441
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
6442
+ 404
6443
+ );
6444
+ }
6445
+ const who = await effectiveUserId(c, ownerNameOf(opts));
6446
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6447
+ const out = await callResumeFor(c, who.userId, "/resume/api/tailored-resume", {
6448
+ job_title: job.title,
6449
+ company: job.company,
6450
+ description: job.description,
6451
+ ...typeof opts.profile_type === "string" ? { profile_type: opts.profile_type } : {},
6452
+ ...typeof opts.tailor === "boolean" ? { tailor: opts.tailor } : {}
6453
+ });
6454
+ if ("refusal" in out) return c.json(refusalBody(out.refusal), 409);
6455
+ const res = out.res;
6456
+ if (!res.ok) return c.json(await upstreamError(c, "resume", id, res), 502);
6457
+ const data = await res.json();
6458
+ generated(c, "resume", id);
6459
+ return c.json({ success: true, data }, 200);
6460
+ });
6461
+ app2.post("/jobs/:id/cover-letter", async (c) => {
6462
+ const id = c.req.param("id");
6463
+ const opts = await readOptions(c);
6464
+ const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
6465
+ if (!job) {
6466
+ return c.json(
6467
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
6468
+ 404
6469
+ );
6470
+ }
6471
+ const who = await effectiveUserId(c, ownerNameOf(opts));
6472
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6473
+ const out = await callResumeFor(c, who.userId, "/resume/api/cover-letter", {
6474
+ job_title: job.title,
6475
+ company: job.company,
6476
+ description: job.description,
6477
+ ...opts.tone === "formal" || opts.tone === "conversational" ? { tone: opts.tone } : {}
6478
+ });
6479
+ if ("refusal" in out) return c.json(refusalBody(out.refusal), 409);
6480
+ const res = out.res;
6481
+ if (!res.ok) return c.json(await upstreamError(c, "cover_letter", id, res), 502);
6482
+ const data = await res.json();
6483
+ generated(c, "cover_letter", id);
6484
+ return c.json({ success: true, data }, 200);
6485
+ });
6486
+ app2.post("/jobs/:id/packet-link", gateAuthed);
6487
+ app2.post("/jobs/:id/packet-link", async (c) => {
6488
+ const id = c.req.param("id");
6489
+ const opts = await readOptions(c);
6490
+ const resumeMarkdown = typeof opts.resume_markdown === "string" ? opts.resume_markdown : "";
6491
+ if (!resumeMarkdown) {
6492
+ return c.json(
6493
+ { success: false, error: "Bad request", message: "resume_markdown is required" },
6494
+ 400
6495
+ );
6496
+ }
6497
+ const coverLetterMarkdown = typeof opts.cover_letter_markdown === "string" ? opts.cover_letter_markdown : void 0;
6498
+ const ttlDays = typeof opts.ttl_days === "number" ? opts.ttl_days : 365;
6499
+ const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
6500
+ if (!job) {
6501
+ return c.json(
6502
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
6503
+ 404
6504
+ );
6505
+ }
6506
+ const who = await effectiveUserId(c, ownerNameOf(opts));
6507
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6508
+ const out = await callResumeFor(c, who.userId, "/resume/api/variants", {
6509
+ label: `${job.company} - ${job.title}`,
6510
+ markdown: resumeMarkdown,
6511
+ ...coverLetterMarkdown ? { cover_letter_markdown: coverLetterMarkdown } : {},
6512
+ company: job.company,
6513
+ job_title: job.title,
6514
+ ttl_days: ttlDays
6515
+ });
6516
+ if ("refusal" in out) return c.json(refusalBody(out.refusal), 409);
6517
+ const res = out.res;
6518
+ if (!res.ok) return c.json(await upstreamError(c, "packet_link", id, res), 502);
6519
+ const variant = await res.json();
6520
+ if (!variant.slug) {
6521
+ return c.json(
6522
+ {
6523
+ success: false,
6524
+ error: "Upstream error",
6525
+ message: "resume-api returned no slug"
6526
+ },
6527
+ 502
6269
6528
  );
6270
6529
  }
6271
- );
6272
- app2.openapi(
6273
- createRoute({
6274
- method: "delete",
6275
- path: "/application-answers/{key}",
6276
- tags: ["Answers"],
6277
- summary: "Forget one standing answer",
6278
- request: {
6279
- params: z.object({ key: z.string() }),
6280
- // No body on a DELETE, so the query string is the only way to name
6281
- // an owner here — unlike the PUT, which reads either and prefers
6282
- // the body.
6283
- query: ownerNameQuery
6284
- },
6285
- responses: {
6286
- 200: {
6287
- description: "Deleted (or was already absent)",
6288
- content: { "application/json": { schema: AnswersResponseSchema } }
6289
- },
6290
- 403: {
6291
- description: "Forbidden",
6292
- content: { "application/json": { schema: ErrorResponseSchema } }
6293
- },
6294
- 404: {
6295
- description: "No such owner name",
6296
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6297
- },
6298
- 409: {
6299
- description: "That owner name has never signed in",
6300
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6301
- },
6302
- 503: {
6303
- description: "Identity could not be resolved right now — retry",
6304
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6305
- }
6306
- }
6307
- }),
6308
- async (c) => {
6309
- const { ownerName } = c.req.valid("query");
6310
- const who = await effectiveUserId(c, ownerName);
6311
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6530
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6531
+ const db = c.env.JOB_PLATFORM_DB;
6532
+ await db.batch([
6533
+ db.prepare(
6534
+ `INSERT INTO job_events
6535
+ (job_id, user_id, kind, from_state, to_state, note, occurred_at, created_at)
6536
+ SELECT ?1, ?2, 'state', NULL, 'saved', NULL, ?3, ?3
6537
+ WHERE NOT EXISTS (SELECT 1 FROM job_states WHERE job_id = ?1 AND user_id = ?2)`
6538
+ ).bind(id, who.userId, now),
6539
+ db.prepare(
6540
+ `INSERT INTO job_states (job_id, user_id, state, notes, updated_at, variant_slug)
6541
+ VALUES (?, ?, 'saved', NULL, ?, ?)
6542
+ ON CONFLICT (job_id, user_id) DO UPDATE SET
6543
+ variant_slug = excluded.variant_slug,
6544
+ updated_at = excluded.updated_at`
6545
+ ).bind(id, who.userId, now, variant.slug)
6546
+ ]);
6547
+ const url = `https://hadoku.me/resume?v=${encodeURIComponent(variant.slug)}`;
6548
+ generated(c, "packet_link", id, { slug: variant.slug, user_id: who.userId });
6549
+ return c.json({ success: true, data: { slug: variant.slug, url } }, 200);
6550
+ });
6551
+ app2.post("/jobs/:id/application-extras", gateAuthed);
6552
+ app2.post("/jobs/:id/application-extras", async (c) => {
6553
+ const id = c.req.param("id");
6554
+ const opts = await readOptions(c);
6555
+ let resumeMarkdown = typeof opts.resume_markdown === "string" ? opts.resume_markdown : "";
6556
+ const who = await effectiveUserId(c, ownerNameOf(opts));
6557
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6558
+ if (!resumeMarkdown) {
6312
6559
  const userId = who.userId;
6313
- const { key } = c.req.valid("param");
6314
- const db = c.env.JOB_PLATFORM_DB;
6315
- await db.prepare("DELETE FROM application_answers WHERE user_id = ? AND question_key = ?").bind(userId, key).run();
6316
- const rows = await db.prepare(
6317
- `SELECT question_key, question, answer, updated_at
6318
- FROM application_answers WHERE user_id = ? ORDER BY updated_at DESC`
6319
- ).bind(userId).all();
6320
- return c.json({ success: true, data: { answers: rows.results } }, 200);
6321
- }
6322
- );
6323
- app2.openapi(
6324
- createRoute({
6325
- method: "get",
6326
- path: "/unanswered-questions",
6327
- tags: ["Answers"],
6328
- summary: "Questions the runner could not answer, most costly first",
6329
- request: {
6330
- query: ownerNameQuery
6331
- },
6332
- responses: {
6333
- 200: {
6334
- description: "The queue",
6335
- content: { "application/json": { schema: UnansweredResponseSchema } }
6336
- },
6337
- 403: {
6338
- description: "Forbidden",
6339
- content: { "application/json": { schema: ErrorResponseSchema } }
6340
- },
6341
- 404: {
6342
- description: "No such owner name",
6343
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6344
- },
6345
- 409: {
6346
- description: "That owner name has never signed in",
6347
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6348
- },
6349
- 503: {
6350
- description: "Identity could not be resolved right now — retry",
6351
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6352
- }
6353
- }
6354
- }),
6355
- async (c) => {
6356
- const { ownerName } = c.req.valid("query");
6357
- const who = await effectiveUserId(c, ownerName);
6358
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6359
- const questions = await unansweredQuestions(c.env.JOB_PLATFORM_DB, who.userId);
6360
- return c.json({ success: true, data: { questions } }, 200);
6361
- }
6362
- );
6363
- }
6364
- function registerOwnerRoutes(app2) {
6365
- app2.post("/applications/:id/owner", gateAuthed);
6366
- app2.openapi(
6367
- createRoute({
6368
- method: "post",
6369
- path: "/applications/{id}/owner",
6370
- tags: ["Applications"],
6371
- summary: "Hand an application to another user, named by display name",
6372
- request: {
6373
- params: z.object({ id: z.string() }),
6374
- body: { content: { "application/json": { schema: ReassignOwnerInputSchema } } }
6375
- },
6376
- responses: {
6377
- 200: {
6378
- description: "Reassigned",
6379
- content: { "application/json": { schema: ReassignOwnerResponseSchema } }
6380
- },
6381
- 403: {
6382
- description: "Forbidden",
6383
- content: { "application/json": { schema: ErrorResponseSchema } }
6384
- },
6385
- 400: {
6386
- description: "The name was empty or otherwise unusable",
6387
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6388
- },
6389
- 404: {
6390
- description: "No such application, not yours, or no such name",
6391
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6392
- },
6393
- 409: {
6394
- description: "That name has never signed in, so it has no userId to own rows",
6395
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6396
- },
6397
- 503: {
6398
- description: "Identity could not be resolved right now — retry",
6399
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6400
- }
6401
- }
6402
- }),
6403
- async (c) => {
6404
- const callerId = await maybeUserId(c);
6405
- if (!callerId) {
6406
- return c.json(
6407
- { success: false, error: "Forbidden", message: "Authentication required" },
6408
- 403
6409
- );
6410
- }
6411
- const { id } = c.req.valid("param");
6412
- const { name } = c.req.valid("json");
6413
- const db = c.env.JOB_PLATFORM_DB;
6414
- const isAdmin = tierAtLeast(c.get("authContext"), "admin");
6415
- const row = await db.prepare("SELECT user_id, job_id FROM applications WHERE id = ?").bind(id).first();
6416
- if (!row || row.user_id !== callerId && !isAdmin) {
6560
+ const row = userId ? await c.env.JOB_PLATFORM_DB.prepare(
6561
+ "SELECT variant_slug FROM job_states WHERE job_id = ? AND user_id = ?"
6562
+ ).bind(id, userId).first() : null;
6563
+ const slug2 = row?.variant_slug ?? null;
6564
+ if (!slug2) {
6417
6565
  return c.json(
6418
6566
  {
6419
6567
  success: false,
6420
- error: "Not found",
6421
- message: `Application '${id}' not found`
6568
+ error: "Bad request",
6569
+ message: "resume_markdown is required, or prepare a packet for this job first — no minted packet was found for this caller."
6422
6570
  },
6423
- 404
6571
+ 400
6424
6572
  );
6425
6573
  }
6426
- const resolved = await resolveOwnerName(
6427
- c.env.JOB_PLATFORM_DB,
6428
- c.env.EDGE,
6429
- c.env.HADOKU_SERVICE_KEY ?? "",
6430
- name,
6431
- Date.now(),
6432
- (label2, work) => runAfterResponse(c, label2, work)
6433
- );
6434
- if (isIdentityError(resolved)) {
6435
- const status = [400, 404, 409, 503].includes(resolved.status) ? resolved.status : 503;
6574
+ const minted = await fetchMintedResume(c.env, slug2);
6575
+ if ("expired" in minted) {
6436
6576
  return c.json(
6437
6577
  {
6438
6578
  success: false,
6439
- error: status === 503 ? "Unavailable" : status === 409 ? "Conflict" : "Not found",
6440
- message: resolved.error,
6441
- ...resolved.code ? { code: resolved.code } : {}
6579
+ error: "Bad request",
6580
+ message: `The packet for this job ('${slug2}') has expired; re-prepare it or post resume_markdown.`
6442
6581
  },
6443
- status
6582
+ 400
6444
6583
  );
6445
6584
  }
6446
- const now = (/* @__PURE__ */ new Date()).toISOString();
6447
- await db.batch([
6448
- db.prepare("UPDATE applications SET user_id = ?, updated_at = ? WHERE id = ?").bind(resolved.userId, now, id),
6449
- db.prepare(
6450
- `INSERT OR REPLACE INTO job_states (job_id, user_id, state, notes, updated_at, variant_slug,
6451
- priority, follow_up_at, contact_name, contact_email)
6452
- SELECT job_id, ?, state, notes, ?, variant_slug,
6453
- priority, follow_up_at, contact_name, contact_email
6454
- FROM job_states WHERE job_id = ? AND user_id = ?`
6455
- ).bind(resolved.userId, now, row.job_id, row.user_id)
6456
- ]);
6457
- recordEvent(c, {
6458
- level: "info",
6459
- event: "application.handed_off",
6460
- message: `${id}: to ${resolved.name}`,
6461
- context: {
6462
- application_id: id,
6463
- job_id: row.job_id,
6464
- from_user_id: row.user_id,
6465
- to_user_id: resolved.userId
6466
- }
6467
- });
6585
+ resumeMarkdown = minted.markdown;
6586
+ }
6587
+ const job = await loadTailoringFields(c.env.JOB_PLATFORM_DB, id);
6588
+ if (!job) {
6468
6589
  return c.json(
6469
- {
6470
- success: true,
6471
- data: {
6472
- application_id: id,
6473
- // The echo IS the point (R4): the caller sees which identity
6474
- // they actually hit, for the one change they cannot undo alone.
6475
- grantedTo: { name: resolved.name, tier: resolved.tier ?? null }
6476
- }
6477
- },
6478
- 200
6590
+ { success: false, error: "Not found", message: `Job '${id}' not found` },
6591
+ 404
6479
6592
  );
6480
6593
  }
6481
- );
6594
+ const out = await callResumeFor(c, who.userId, "/resume/api/application-extras", {
6595
+ job_title: job.title,
6596
+ company: job.company,
6597
+ description: job.description,
6598
+ resume_markdown: resumeMarkdown,
6599
+ // The kit's location answers must speak to THIS job's location, not the
6600
+ // candidate's default metro — resume-api injects these into its prompt.
6601
+ job_location: job.location ?? void 0,
6602
+ workplace_type: job.workplace_type ?? void 0,
6603
+ questions: questionsOf(opts)
6604
+ });
6605
+ if ("refusal" in out) return c.json(refusalBody(out.refusal), 409);
6606
+ const res = out.res;
6607
+ if (!res.ok) return c.json(await upstreamError(c, "application_extras", id, res), 502);
6608
+ const data = await res.json();
6609
+ generated(c, "application_extras", id);
6610
+ return c.json({ success: true, data }, 200);
6611
+ });
6482
6612
  }
6483
- function formUrl(job) {
6484
- const own = job.id.slice(job.id.indexOf("_") + 1);
6485
- if (job.slug && job.id.startsWith("greenhouse_") && /^\d+$/.test(own)) {
6486
- return `https://job-boards.greenhouse.io/embed/job_app?for=${encodeURIComponent(job.slug)}&token=${own}`;
6487
- }
6488
- if (job.slug && job.id.startsWith("ashby_")) {
6489
- return `https://jobs.ashbyhq.com/${encodeURIComponent(job.slug)}/${own}/application`;
6613
+ const COMMON_QUESTIONS = [
6614
+ { question: "Veteran Status", seenOn: 15 },
6615
+ { question: "Disability Status", seenOn: 13 },
6616
+ { question: "Are you Hispanic/Latino?", seenOn: 13 },
6617
+ { question: "Location (City)", seenOn: 12 },
6618
+ { question: "Preferred First Name", seenOn: 11 },
6619
+ { question: "How did you hear about this job?", seenOn: 6 },
6620
+ { question: "Are you legally authorized to work in the United States?", seenOn: 3 },
6621
+ {
6622
+ question: "Are you legally authorized to work in the country where the job is located?",
6623
+ seenOn: 2
6624
+ },
6625
+ {
6626
+ question: "Will you now or in the future require company sponsorship to retain or extend your work authorization?",
6627
+ seenOn: 2
6628
+ },
6629
+ { question: "I identify my gender as", seenOn: 2 },
6630
+ { question: "Are you at least 18 years of age?", seenOn: 1 },
6631
+ { question: "Agreement to Arbitrate", seenOn: 1 }
6632
+ ];
6633
+ const FOREIGN = /\b(canada|canadian|quebec|ireland|irish|uk|united kingdom|britain|england|scotland|germany|france|india|australia|mexico|brazil|japan|singapore|netherlands|spain|israel|poland|china|emea|europe|apac|latam)\b/;
6634
+ const LEGAL = /\b(agree|agreement|certify|consent|acknowledge|arbitrat\w*|privacy|terms of service|confirm receipt|attest|personal data)\b/;
6635
+ const CONDITIONAL = /^if\b|\bif you (do|did|selected|answered|chose|said|have|are|were)\b|\bplease (list|share|explain|describe|specify|provide)\b/;
6636
+ function isFollowUp(question) {
6637
+ return /^if\b|\bif you (do|did|selected|answered|chose|said)\b/.test(questionKey(question));
6638
+ }
6639
+ const RULES = [
6640
+ {
6641
+ id: "sponsorship",
6642
+ label: "Visa sponsorship",
6643
+ match: (h) => /\bsponsor/.test(h) || /\b(visa|immigration)\b/.test(h) && /\b(require|need)\b/.test(h),
6644
+ sensitive: true
6645
+ },
6646
+ {
6647
+ id: "work_authorization",
6648
+ label: "Authorized to work",
6649
+ match: (h) => /\b(authori[sz]ed|eligible|entitled|right)\b/.test(h) && /\bto work\b/.test(h),
6650
+ sensitive: true
6651
+ },
6652
+ {
6653
+ id: "race_ethnicity",
6654
+ label: "Race / ethnicity",
6655
+ match: (h) => /\b(race|racial|ethnicity|ethnic)\b/.test(h),
6656
+ sensitive: false
6657
+ },
6658
+ {
6659
+ id: "hispanic_latino",
6660
+ label: "Hispanic / Latino",
6661
+ match: (h) => /\b(hispanic|latino|latina|latinx)\b/.test(h),
6662
+ sensitive: false
6663
+ },
6664
+ {
6665
+ id: "veteran",
6666
+ label: "Veteran status",
6667
+ match: (h) => /\b(veteran|military|armed forces)\b/.test(h),
6668
+ sensitive: false
6669
+ },
6670
+ { id: "disability", label: "Disability", match: (h) => /\bdisabilit/.test(h), sensitive: false },
6671
+ { id: "lgbtq", label: "LGBTQ+", match: (h) => /\blgbt/.test(h), sensitive: false },
6672
+ {
6673
+ id: "current_employer",
6674
+ label: "Current employer",
6675
+ // "current", not "currently": "Are you currently employed by an Aledade
6676
+ // Partner Practice?" is a different question with a different answer.
6677
+ //
6678
+ // ADJACENT words, not "current … company" anywhere. The loose form put
6679
+ // "Are you a current government official or … a company …" in this
6680
+ // family, and its answer — "No, I am not a current or former Government
6681
+ // Official" — would have been offered for Most Recent Employer.
6682
+ match: (h) => /\b(current|most recent)( most recent)? (employer|company)\b/.test(h),
6683
+ sensitive: false
6684
+ },
6685
+ {
6686
+ id: "current_title",
6687
+ label: "Current job title",
6688
+ match: (h) => /\b(current|most recent)( most recent)? (job )?title\b/.test(h),
6689
+ sensitive: false
6690
+ },
6691
+ {
6692
+ id: "state_of_residence",
6693
+ label: "State you live in",
6694
+ // Not "plan": "the state you plan to be located in" asks about the
6695
+ // future, and may well differ.
6696
+ match: (h) => /\bstate\b/.test(h) && /\b(reside|live|currently)\b/.test(h) && !/\bplan\b/.test(h),
6697
+ sensitive: false
6698
+ },
6699
+ {
6700
+ id: "postal_code",
6701
+ label: "ZIP / postal code",
6702
+ match: (h) => /\b(zip|postal)\b/.test(h),
6703
+ sensitive: false
6704
+ },
6705
+ {
6706
+ id: "current_city",
6707
+ label: "Where you live",
6708
+ match: (h) => /\b(current|currently)\b/.test(h) && /\blocat/.test(h) || /\blocation city\b/.test(h),
6709
+ sensitive: false
6710
+ },
6711
+ {
6712
+ id: "how_heard",
6713
+ label: "How you heard about the role",
6714
+ match: (h) => /\bhow did you (first )?(hear|learn|find)\b/.test(h) || /\bwhere (have|did) you (hear|heard|learn|learned)\b/.test(h),
6715
+ sensitive: false
6716
+ },
6717
+ {
6718
+ id: "worked_here_before",
6719
+ label: "Worked at this company before",
6720
+ // A fact about EACH employer, so the dashboard lists every company and
6721
+ // the owner unticks any they did work for. Grouped because the answer is
6722
+ // "no" for every employer they never worked at, which is nearly all.
6723
+ match: (h) => /\b(previously|formerly|ever|before)\b/.test(h) && /\b(employed|worked)\b/.test(h) || /\bformer\b.*\bemployee\b/.test(h),
6724
+ sensitive: false
6725
+ },
6726
+ {
6727
+ id: "website",
6728
+ label: "Personal website",
6729
+ // Affirm's "Other Links" is the same free slot for a personal site.
6730
+ match: (h) => /^websites?\b/.test(h) || /^other links?$/.test(h),
6731
+ sensitive: false
6732
+ },
6733
+ { id: "github", label: "GitHub profile", match: (h) => /\bgithub\b/.test(h), sensitive: false },
6734
+ {
6735
+ id: "pronouns",
6736
+ label: "Pronouns",
6737
+ // Not a question that also asks for a name — Samsara's "share your
6738
+ // preferred name and pronouns" wants both in one box, and a bare
6739
+ // "He/Him" would answer half of it.
6740
+ match: (h) => /\bpronouns?\b/.test(h) && !/\bname\b/.test(h),
6741
+ sensitive: false
6490
6742
  }
6491
- if (job.slug && job.id.startsWith("lever_")) {
6492
- return `https://jobs.lever.co/${encodeURIComponent(job.slug)}/${own}/apply`;
6743
+ ];
6744
+ function head(question) {
6745
+ return questionKey(question.split("?")[0] ?? "") || questionKey(question);
6746
+ }
6747
+ function questionFamily(question) {
6748
+ const full = questionKey(question);
6749
+ if (!full || LEGAL.test(full) || CONDITIONAL.test(full)) return null;
6750
+ const h = head(question);
6751
+ for (const rule of RULES) {
6752
+ if (!rule.match(h)) continue;
6753
+ if (rule.sensitive && (FOREIGN.test(h) || questionNegated(questionTerms(h)))) return null;
6754
+ return { id: rule.id, label: rule.label };
6493
6755
  }
6494
- return job.url;
6756
+ return null;
6495
6757
  }
6496
- function parseEvidence(raw) {
6497
- if (raw === null) return null;
6498
- try {
6499
- const parsed = JSON.parse(raw);
6500
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
6501
- } catch {
6502
- return null;
6758
+ const US_NAMES = /* @__PURE__ */ new Set([
6759
+ "us",
6760
+ "u s",
6761
+ "usa",
6762
+ "u s a",
6763
+ "america",
6764
+ "united states",
6765
+ "united states of america",
6766
+ "the united states",
6767
+ "the united states of america"
6768
+ ]);
6769
+ function matchOption(answer, options) {
6770
+ const a = answer.trim();
6771
+ if (!a) return null;
6772
+ if (options.length === 0) return a;
6773
+ const na = questionKey(a);
6774
+ const exact = options.filter((o) => questionKey(o) === na);
6775
+ if (exact.length === 1) return exact[0] ?? null;
6776
+ if (US_NAMES.has(na)) {
6777
+ const us = options.filter((o) => US_NAMES.has(questionKey(o).replace(/( [0-9]+)+$/, "")));
6778
+ if (us.length === 1) return us[0] ?? null;
6779
+ }
6780
+ const lead = na.split(" ")[0];
6781
+ if (lead === "yes" || lead === "no") {
6782
+ const same = options.filter((o) => questionKey(o).split(" ")[0] === lead);
6783
+ return same.length === 1 ? same[0] ?? null : null;
6503
6784
  }
6785
+ const within = (hay, needle) => ` ${hay} `.includes(` ${needle} `);
6786
+ const hits = options.filter((o) => {
6787
+ const no = questionKey(o);
6788
+ return within(no, na) || within(na, no);
6789
+ });
6790
+ return hits.length === 1 ? hits[0] ?? null : null;
6504
6791
  }
6505
- function toApplication(row) {
6792
+ const MIN_SHARED_TERMS = 2;
6793
+ const MAX_SIMILAR = 4;
6794
+ function familyFields(question, options, familyAnswers, saved) {
6795
+ const fam = questionFamily(question);
6796
+ const prior = fam ? familyAnswers.get(fam.id) ?? [] : [];
6797
+ const basis = saved ?? prior[0] ?? null;
6506
6798
  return {
6507
- id: row.id,
6508
- job_id: row.job_id,
6509
- variant_slug: row.variant_slug,
6510
- mode: row.mode,
6511
- status: row.status,
6512
- error: row.error,
6513
- evidence: parseEvidence(row.evidence),
6514
- approved_fingerprint: row.approved_fingerprint,
6515
- created_at: row.created_at,
6516
- updated_at: row.updated_at
6799
+ family: fam?.id ?? null,
6800
+ family_label: fam?.label ?? null,
6801
+ family_answers: prior,
6802
+ suggested: basis ? matchOption(basis, options) : null
6517
6803
  };
6518
6804
  }
6519
- function reconcile(evidence, stored) {
6520
- const out = { answered_since: [], still_unanswered: [], overridden: [] };
6521
- if (!evidence) return out;
6522
- const unmatched = Array.isArray(evidence.unmatched) ? evidence.unmatched : [];
6523
- for (const raw of unmatched) {
6524
- if (typeof raw !== "string" || !raw.trim()) continue;
6525
- const hit = stored.get(questionKey(raw));
6526
- if (hit) out.answered_since.push({ question: raw, answer: hit.answer });
6527
- else out.still_unanswered.push(raw);
6528
- }
6529
- const answers = evidence.answers;
6530
- if (typeof answers === "object" && answers !== null && !Array.isArray(answers)) {
6531
- for (const [key, filled] of Object.entries(answers)) {
6532
- if (typeof filled !== "string") continue;
6533
- const hit = stored.get(key);
6534
- if (hit && hit.answer !== filled) {
6535
- out.overridden.push({ question: hit.question, filled, stored: hit.answer });
6536
- }
6805
+ function findSimilar(pendingKey, pendingQuestion, answered) {
6806
+ const pendingTerms = questionTerms(pendingKey);
6807
+ if (pendingTerms.size === 0) return [];
6808
+ const pendingNeg = questionNegated(pendingTerms);
6809
+ const pendingFam = questionFamily(pendingQuestion)?.id ?? null;
6810
+ const scored = [];
6811
+ for (const a of answered) {
6812
+ const terms = questionTerms(a.question_key);
6813
+ if (terms.size === 0) continue;
6814
+ if ((questionFamily(a.question)?.id ?? null) !== pendingFam && questionNegated(terms) === pendingNeg) {
6815
+ continue;
6537
6816
  }
6817
+ const shared = [...pendingTerms].filter((t) => terms.has(t));
6818
+ if (shared.length < MIN_SHARED_TERMS) continue;
6819
+ const onlyPending = [...pendingTerms].filter((t) => !terms.has(t));
6820
+ const onlyAnswered = [...terms].filter((t) => !pendingTerms.has(t));
6821
+ const answeredNeg = questionNegated(terms);
6822
+ scored.push({
6823
+ question_key: a.question_key,
6824
+ question: a.question,
6825
+ answer: a.answer,
6826
+ shared_terms: shared.sort(),
6827
+ only_in_pending: onlyPending.sort(),
6828
+ only_in_answered: onlyAnswered.sort(),
6829
+ polarity_differs: pendingNeg !== answeredNeg,
6830
+ // The runner's own rule, reported rather than acted on: every
6831
+ // meaningful word of the pending question is already in the stored
6832
+ // one, and polarity agrees.
6833
+ runner_would_match: pendingTerms.size >= 2 && onlyPending.length === 0 && pendingNeg === answeredNeg,
6834
+ // Jaccard: rewards overlap but penalises each side's leftovers, so a
6835
+ // short generic question does not top the list against everything.
6836
+ score: shared.length / (pendingTerms.size + terms.size - shared.length)
6837
+ });
6538
6838
  }
6539
- return out;
6540
- }
6541
- async function delistedReason(db, jobId) {
6542
- const job = await db.prepare("SELECT ats, slug, last_seen_at FROM jobs WHERE id = ?").bind(jobId).first();
6543
- if (!job?.ats || !job.slug || !job.last_seen_at) return null;
6544
- const newest = (await boardNewest(db, [job])).values().next().value ?? null;
6545
- if (!isDelisted(job.last_seen_at, newest)) return null;
6546
- return `this posting has not appeared in a scrape of the ${job.ats} board '${job.slug}' since ${job.last_seen_at}, while other jobs on that board were seen as recently as ${newest} — it looks taken down`;
6839
+ return scored.sort((a, b) => b.score - a.score).slice(0, MAX_SIMILAR).map(({ score: _score, ...rest }) => rest);
6547
6840
  }
6548
- const FORBIDDEN = {
6549
- success: false,
6550
- error: "Forbidden",
6551
- message: "Authentication required"
6552
- };
6553
- function registerApplicationRoutes(app2) {
6554
- app2.post("/jobs/:id/apply", gateAuthed);
6555
- app2.get("/applications", gateAuthed);
6556
- app2.post("/applications/:id/status", gateAuthed);
6557
- app2.post("/applications/:id/approve", gateAuthed);
6558
- app2.openapi(
6559
- createRoute({
6560
- method: "post",
6561
- path: "/jobs/{id}/apply",
6562
- tags: ["Applications"],
6563
- summary: "Queue this job for the form runner (the packet is minted at fill, not here)",
6564
- request: {
6565
- params: z.object({ id: z.string() }),
6566
- query: ownerNameQuery,
6567
- body: {
6568
- content: { "application/json": { schema: ApplyRequestSchema } },
6569
- required: false
6570
- }
6571
- },
6572
- responses: {
6573
- 200: {
6574
- description: "Application queued",
6575
- content: { "application/json": { schema: ApplicationResponseSchema } }
6576
- },
6577
- 403: {
6578
- description: "Forbidden",
6579
- content: { "application/json": { schema: ErrorResponseSchema } }
6580
- },
6581
- 404: {
6582
- description: "Job not found",
6583
- content: { "application/json": { schema: ErrorResponseSchema } }
6584
- },
6585
- 422: {
6586
- description: "The posting was typed in by hand with no link",
6587
- content: { "application/json": { schema: ErrorResponseSchema } }
6588
- },
6589
- 409: {
6590
- description: "The posting looks taken down (retry with force), the row is approved (retry with force) or already submitted, or the owner name has never signed in",
6591
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6592
- },
6593
- 503: {
6594
- description: "Identity could not be resolved right now — retry",
6595
- content: { "application/json": { schema: IdentityErrorResponseSchema } }
6596
- }
6597
- }
6598
- }),
6599
- async (c) => {
6600
- const { id } = c.req.valid("param");
6601
- const body = c.req.valid("json");
6602
- const mode = body?.mode ?? "review";
6603
- const who = await effectiveUserId(c, body?.ownerName);
6604
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6605
- const userId = who.userId;
6606
- const db = c.env.JOB_PLATFORM_DB;
6607
- const job = await db.prepare("SELECT id, url FROM jobs WHERE id = ?").bind(id).first();
6608
- if (!job) {
6609
- return c.json(
6610
- { success: false, error: "Not found", message: `Job '${id}' not found` },
6611
- 404
6841
+ async function unansweredQuestions(db, userId) {
6842
+ const rows = await db.prepare(
6843
+ `SELECT a.evidence, a.status, a.updated_at, j.company
6844
+ FROM applications a
6845
+ JOIN jobs j ON j.id = a.job_id
6846
+ WHERE a.user_id = ? AND a.evidence IS NOT NULL`
6847
+ ).bind(userId).all();
6848
+ const answered = await db.prepare(
6849
+ `SELECT question_key, question, answer, updated_at FROM application_answers
6850
+ WHERE user_id = ? ORDER BY updated_at DESC`
6851
+ ).bind(userId).all();
6852
+ const known = new Set(answered.results.map((r) => r.question_key));
6853
+ const savedAnswer = new Map(answered.results.map((r) => [r.question_key, r.answer]));
6854
+ const savedAt = new Map(answered.results.map((r) => [r.question_key, r.updated_at]));
6855
+ const familyAnswers = /* @__PURE__ */ new Map();
6856
+ for (const a of answered.results) {
6857
+ const fam = questionFamily(a.question);
6858
+ if (!fam || !a.answer.trim()) continue;
6859
+ const list = familyAnswers.get(fam.id) ?? [];
6860
+ if (!list.some((x) => x.toLowerCase() === a.answer.trim().toLowerCase()))
6861
+ list.push(a.answer.trim());
6862
+ familyAnswers.set(fam.id, list);
6863
+ }
6864
+ const learnedOptions = /* @__PURE__ */ new Map();
6865
+ const pending = /* @__PURE__ */ new Map();
6866
+ const learnedMulti = /* @__PURE__ */ new Set();
6867
+ for (const row of rows.results) {
6868
+ let unmatched;
6869
+ let blockingKeys = null;
6870
+ let optionsByKey = {};
6871
+ try {
6872
+ const parsedEvidence = JSON.parse(row.evidence);
6873
+ unmatched = parsedEvidence.unmatched;
6874
+ if (Array.isArray(parsedEvidence.blocking)) {
6875
+ blockingKeys = new Set(
6876
+ parsedEvidence.blocking.filter((b) => typeof b === "string").map((b) => questionKey(b))
6612
6877
  );
6613
6878
  }
6614
- const refuse = (reason) => recordEvent(c, {
6615
- level: "warn",
6616
- event: "application.queue_refused",
6617
- message: `${id}: ${reason}`,
6618
- context: { job_id: id, user_id: userId, reason }
6619
- });
6620
- if (publicUrl(job.url) === null) {
6621
- refuse("no link");
6622
- return c.json(
6623
- {
6624
- success: false,
6625
- error: "Unprocessable",
6626
- message: "This posting has no link, so the runner has no form to fill."
6627
- },
6628
- 422
6629
- );
6879
+ const opts = parsedEvidence.options;
6880
+ if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) {
6881
+ optionsByKey = opts;
6630
6882
  }
6631
- if (!body?.force) {
6632
- const delisted = await delistedReason(db, id);
6633
- if (delisted) {
6634
- refuse(`delisted: ${delisted}`);
6635
- return c.json(
6636
- {
6637
- success: false,
6638
- error: "Conflict",
6639
- message: `${delisted}. Re-apply with {"force": true} if it is still open.`
6640
- },
6641
- 409
6642
- );
6883
+ if (Array.isArray(parsedEvidence.multi)) {
6884
+ for (const k of parsedEvidence.multi) {
6885
+ if (typeof k === "string" && k) learnedMulti.add(questionKey(k));
6643
6886
  }
6644
6887
  }
6645
- const state = await db.prepare("SELECT variant_slug FROM job_states WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
6646
- const variantSlug = state?.variant_slug ?? "";
6647
- const existing = await db.prepare("SELECT status FROM applications WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
6648
- if (existing?.status === "submitted" || existing?.status === "approved" && !body?.force) {
6649
- refuse(`already ${existing.status}`);
6650
- return c.json(
6651
- {
6652
- success: false,
6653
- error: "Conflict",
6654
- message: existing.status === "submitted" ? "This application was already submitted." : 'This application is approved; re-queueing would discard the approval. Re-apply with {"force": true} to fill it again.'
6655
- },
6656
- 409
6657
- );
6888
+ } catch {
6889
+ continue;
6890
+ }
6891
+ for (const [key, seen] of Object.entries(optionsByKey)) {
6892
+ if (learnedOptions.has(key) || !Array.isArray(seen)) continue;
6893
+ const clean = seen.filter((o) => typeof o === "string" && !!o);
6894
+ if (clean.length) learnedOptions.set(key, clean);
6895
+ }
6896
+ if (!Array.isArray(unmatched)) continue;
6897
+ for (const raw of unmatched) {
6898
+ if (typeof raw !== "string" || !raw.trim()) continue;
6899
+ const key = questionKey(raw);
6900
+ if (!key) continue;
6901
+ const rejected = known.has(key) && row.status === "needs_manual" && blockingKeys !== null && blockingKeys.has(key) && (savedAt.get(key) ?? "") <= row.updated_at;
6902
+ if (known.has(key) && !rejected) continue;
6903
+ const entry = pending.get(key) ?? {
6904
+ question: raw.trim(),
6905
+ companies: /* @__PURE__ */ new Set(),
6906
+ applications: 0,
6907
+ blocking: 0,
6908
+ options: [],
6909
+ optionsFromBlocker: false,
6910
+ savedAnswer: rejected ? savedAnswer.get(key) ?? null : null
6911
+ };
6912
+ const seenHere = optionsByKey[key];
6913
+ const own = Array.isArray(seenHere) ? seenHere.filter((o) => typeof o === "string" && !!o) : [];
6914
+ const blocksHere = row.status === "needs_manual" && (blockingKeys === null || blockingKeys.has(key));
6915
+ if (blocksHere && own.length && !entry.optionsFromBlocker) {
6916
+ entry.options = own;
6917
+ entry.optionsFromBlocker = true;
6918
+ } else if (!entry.options.length) {
6919
+ entry.options = own.length ? own : learnedOptions.get(key) ?? [];
6658
6920
  }
6659
- const now = (/* @__PURE__ */ new Date()).toISOString();
6660
- await db.prepare(
6661
- `INSERT INTO applications
6662
- (id, user_id, job_id, variant_slug, mode, status, error, evidence, created_at, updated_at)
6663
- VALUES (?, ?, ?, ?, ?, 'queued', NULL, NULL, ?, ?)
6664
- ON CONFLICT (user_id, job_id) DO UPDATE SET
6665
- -- An empty slug means "not minted yet" and must never overwrite a
6666
- -- real pin: re-queueing a row whose packet already exists has to
6667
- -- keep pointing at that packet. Same shape as the COALESCE on
6668
- -- job_states.variant_slug, for the same reason.
6669
- variant_slug = COALESCE(NULLIF(excluded.variant_slug, ''), applications.variant_slug),
6670
- mode = excluded.mode,
6671
- status = 'queued',
6672
- error = NULL,
6673
- evidence = NULL,
6674
- approved_fingerprint = NULL,
6675
- updated_at = excluded.updated_at`
6676
- ).bind(crypto.randomUUID(), userId, id, variantSlug, mode, now, now).run();
6677
- const row = await db.prepare("SELECT * FROM applications WHERE user_id = ? AND job_id = ?").bind(userId, id).first();
6678
- if (!row) throw new Error(`application row missing after upsert (job '${id}')`);
6679
- recordEvent(c, {
6680
- level: "info",
6681
- event: "application.queued",
6682
- message: `${id}: ${existing ? `re-queued from ${existing.status}` : "queued"} (${mode})`,
6683
- context: {
6684
- job_id: id,
6685
- application_id: row.id,
6686
- user_id: userId,
6687
- mode,
6688
- force: Boolean(body?.force),
6689
- previous: existing?.status ?? null,
6690
- on_behalf: who.onBehalfOf ?? null
6691
- }
6692
- });
6693
- return c.json({ success: true, data: { application: toApplication(row) } }, 200);
6921
+ entry.companies.add(row.company);
6922
+ entry.applications += 1;
6923
+ if (row.status === "needs_manual" && (blockingKeys === null || blockingKeys.has(key))) {
6924
+ entry.blocking += 1;
6925
+ }
6926
+ pending.set(key, entry);
6694
6927
  }
6695
- );
6928
+ }
6929
+ for (const { question } of COMMON_QUESTIONS) {
6930
+ const key = questionKey(question);
6931
+ if (!key || known.has(key) || pending.has(key)) continue;
6932
+ pending.set(key, {
6933
+ question,
6934
+ companies: /* @__PURE__ */ new Set(),
6935
+ applications: 0,
6936
+ blocking: 0,
6937
+ // A seed carries no company, but it may still have options: a fill
6938
+ // that ANSWERED this question still learnt what it accepts. That is
6939
+ // the whole reason `learnedOptions` is built separately.
6940
+ options: learnedOptions.get(key) ?? [],
6941
+ optionsFromBlocker: false,
6942
+ savedAnswer: null
6943
+ });
6944
+ }
6945
+ return [...pending.entries()].filter(([, v]) => v.blocking > 0 || !isFollowUp(v.question)).map(([key, v]) => ({
6946
+ question_key: key,
6947
+ question: v.question,
6948
+ companies: [...v.companies].sort(),
6949
+ applications: v.applications,
6950
+ options: v.options,
6951
+ multi: learnedMulti.has(key),
6952
+ blocking: v.blocking,
6953
+ // Every pending question is returned whether or not it looks like a
6954
+ // duplicate — the owner asked to see them all. This only annotates.
6955
+ similar: findSimilar(key, v.question, answered.results),
6956
+ ...familyFields(v.question, v.options, familyAnswers, v.savedAnswer),
6957
+ saved_answer: v.savedAnswer
6958
+ })).sort((a, b) => b.blocking - a.blocking || b.applications - a.applications);
6959
+ }
6960
+ function registerAnswerRoutes(app2) {
6961
+ app2.get("/application-answers", gateAuthed);
6962
+ app2.put("/application-answers", gateAuthed);
6963
+ app2.delete("/application-answers/:key", gateAuthed);
6964
+ app2.get("/unanswered-questions", gateAuthed);
6696
6965
  app2.openapi(
6697
6966
  createRoute({
6698
6967
  method: "get",
6699
- path: "/applications",
6700
- tags: ["Applications"],
6701
- summary: "List the caller's queued applications, newest first",
6968
+ path: "/application-answers",
6969
+ tags: ["Answers"],
6970
+ summary: "The caller's standing answers to application questions",
6702
6971
  request: {
6703
- query: ownerNameQuery.extend({ status: ApplicationStatusSchema.optional() })
6972
+ query: ownerNameQuery
6704
6973
  },
6705
6974
  responses: {
6706
6975
  200: {
6707
- description: "Applications, newest first",
6708
- content: { "application/json": { schema: ApplicationsResponseSchema } }
6976
+ description: "Answers, most recently updated first",
6977
+ content: { "application/json": { schema: AnswersResponseSchema } }
6709
6978
  },
6710
6979
  403: {
6711
6980
  description: "Forbidden",
@@ -6726,77 +6995,42 @@ function registerApplicationRoutes(app2) {
6726
6995
  }
6727
6996
  }),
6728
6997
  async (c) => {
6729
- const { status, ownerName } = c.req.valid("query");
6730
- startTime(c, "who");
6998
+ const { ownerName } = c.req.valid("query");
6731
6999
  const who = await effectiveUserId(c, ownerName);
6732
- endTime(c, "who");
6733
7000
  if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6734
7001
  const userId = who.userId;
6735
- const filter = status ? " AND a.status = ?" : "";
6736
- const stmt = c.env.JOB_PLATFORM_DB.prepare(
6737
- `SELECT a.id, a.job_id, a.variant_slug, a.mode, a.status, a.error,
6738
- a.evidence, a.approved_fingerprint, a.created_at, a.updated_at,
6739
- j.title, j.company, j.location, j.ats, j.slug, j.url
6740
- FROM applications a
6741
- INNER JOIN jobs j ON j.id = a.job_id
6742
- WHERE a.user_id = ?${filter}
6743
- ORDER BY a.updated_at DESC`
6744
- );
6745
- startTime(c, "read");
6746
- const [rows, answerRows] = await c.env.JOB_PLATFORM_DB.batch([
6747
- status ? stmt.bind(userId, status) : stmt.bind(userId),
6748
- c.env.JOB_PLATFORM_DB.prepare(
6749
- "SELECT question_key, question, answer FROM application_answers WHERE user_id = ?"
6750
- ).bind(userId)
6751
- ]);
6752
- endTime(c, "read");
6753
- const appRows = rows.results;
6754
- const answers = answerRows.results;
6755
- const stored = new Map(
6756
- answers.map((a) => [a.question_key, { question: a.question, answer: a.answer }])
6757
- );
6758
- const applications = appRows.map((r) => {
6759
- const app22 = toApplication(r);
6760
- return {
6761
- ...app22,
6762
- title: r.title,
6763
- company: r.company,
6764
- location: r.location,
6765
- form_url: formUrl({ id: r.job_id, ats: r.ats, slug: r.slug, url: r.url }),
6766
- ...reconcile(app22.evidence, stored)
6767
- };
6768
- });
6769
- return c.json(
6770
- {
6771
- success: true,
6772
- data: { applications, owner: { userId, name: who.onBehalfOf } }
6773
- },
6774
- 200
6775
- );
7002
+ const rows = await c.env.JOB_PLATFORM_DB.prepare(
7003
+ `SELECT question_key, question, answer, updated_at
7004
+ FROM application_answers WHERE user_id = ? ORDER BY updated_at DESC`
7005
+ ).bind(userId).all();
7006
+ return c.json({ success: true, data: { answers: rows.results } }, 200);
6776
7007
  }
6777
7008
  );
6778
7009
  app2.openapi(
6779
7010
  createRoute({
6780
- method: "post",
6781
- path: "/applications/{id}/status",
6782
- tags: ["Applications"],
6783
- summary: "Record a status transition (runner endpoint; loose for v1)",
7011
+ method: "put",
7012
+ path: "/application-answers",
7013
+ tags: ["Answers"],
7014
+ summary: "Save (or replace) the answer to one question",
6784
7015
  request: {
6785
- params: z.object({ id: z.string() }),
6786
7016
  query: ownerNameQuery,
6787
- body: { content: { "application/json": { schema: SetApplicationStatusSchema } } }
7017
+ body: { content: { "application/json": { schema: SetAnswerSchema } } }
6788
7018
  },
6789
7019
  responses: {
6790
7020
  200: {
6791
- description: "Status recorded",
6792
- content: { "application/json": { schema: ApplicationResponseSchema } }
7021
+ description: "Saved",
7022
+ content: { "application/json": { schema: AnswerResponseSchema } }
7023
+ },
7024
+ 400: {
7025
+ description: "Empty question",
7026
+ content: { "application/json": { schema: ErrorResponseSchema } }
6793
7027
  },
6794
7028
  403: {
6795
7029
  description: "Forbidden",
6796
7030
  content: { "application/json": { schema: ErrorResponseSchema } }
6797
7031
  },
6798
7032
  404: {
6799
- description: "Application not found, or no such owner name",
7033
+ description: "No such owner name",
6800
7034
  content: { "application/json": { schema: IdentityErrorResponseSchema } }
6801
7035
  },
6802
7036
  409: {
@@ -6810,107 +7044,192 @@ function registerApplicationRoutes(app2) {
6810
7044
  }
6811
7045
  }),
6812
7046
  async (c) => {
6813
- const { id } = c.req.valid("param");
6814
- const body = c.req.valid("json");
6815
- const who = await effectiveUserId(c, body.ownerName);
7047
+ const { question, answer, ownerName } = c.req.valid("json");
7048
+ const who = await effectiveUserId(c, ownerName);
6816
7049
  if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
6817
7050
  const userId = who.userId;
6818
- const db = c.env.JOB_PLATFORM_DB;
6819
- const existing = await db.prepare("SELECT * FROM applications WHERE id = ? AND user_id = ?").bind(id, userId).first();
6820
- if (!existing) {
6821
- recordEvent(c, {
6822
- level: "warn",
6823
- event: "application.status_unknown",
6824
- message: `${id}: ${body.status} for an application not found`,
6825
- context: {
6826
- application_id: id,
6827
- user_id: userId,
6828
- status: body.status,
6829
- error: body.error ?? null
6830
- }
6831
- });
7051
+ const key = questionKey(question);
7052
+ if (!key) {
6832
7053
  return c.json(
6833
7054
  {
6834
7055
  success: false,
6835
- error: "Not found",
6836
- message: `Application '${id}' not found`
7056
+ error: "Bad request",
7057
+ message: "That question has no matchable text"
6837
7058
  },
6838
- 404
7059
+ 400
6839
7060
  );
6840
7061
  }
6841
7062
  const now = (/* @__PURE__ */ new Date()).toISOString();
6842
- const evidence = body.evidence !== void 0 ? JSON.stringify(body.evidence) : existing.evidence;
6843
- const approvedFingerprint = body.status === "submitted" ? existing.approved_fingerprint : null;
6844
- await db.prepare(
6845
- `UPDATE applications SET status = ?, error = ?, evidence = ?,
6846
- approved_fingerprint = ?, updated_at = ?
6847
- WHERE id = ?`
6848
- ).bind(body.status, body.error ?? null, evidence, approvedFingerprint, now, id).run();
6849
- recordEvent(c, {
6850
- level: body.status === "failed" ? "warn" : "info",
6851
- event: "application.status",
6852
- message: `${id}: ${existing.status} -> ${body.status}${body.error ? ` (${body.error.slice(0, 120)})` : ""}`,
6853
- context: {
6854
- application_id: id,
6855
- job_id: existing.job_id,
6856
- user_id: userId,
6857
- from: existing.status,
6858
- to: body.status,
6859
- error: body.error ?? null,
6860
- on_behalf: who.onBehalfOf ?? null
6861
- }
6862
- });
7063
+ await c.env.JOB_PLATFORM_DB.prepare(
7064
+ `INSERT INTO application_answers
7065
+ (user_id, question_key, question, answer, created_at, updated_at)
7066
+ VALUES (?, ?, ?, ?, ?, ?)
7067
+ ON CONFLICT (user_id, question_key) DO UPDATE SET
7068
+ question = excluded.question,
7069
+ answer = excluded.answer,
7070
+ updated_at = excluded.updated_at`
7071
+ ).bind(userId, key, question.trim(), answer, now, now).run();
6863
7072
  return c.json(
6864
7073
  {
6865
7074
  success: true,
6866
7075
  data: {
6867
- application: toApplication({
6868
- ...existing,
6869
- status: body.status,
6870
- error: body.error ?? null,
6871
- evidence,
6872
- approved_fingerprint: approvedFingerprint,
7076
+ answer: {
7077
+ question_key: key,
7078
+ question: question.trim(),
7079
+ answer,
6873
7080
  updated_at: now
6874
- })
7081
+ }
6875
7082
  }
6876
7083
  },
6877
- 200
6878
- );
7084
+ 200
7085
+ );
7086
+ }
7087
+ );
7088
+ app2.openapi(
7089
+ createRoute({
7090
+ method: "delete",
7091
+ path: "/application-answers/{key}",
7092
+ tags: ["Answers"],
7093
+ summary: "Forget one standing answer",
7094
+ request: {
7095
+ params: z.object({ key: z.string() }),
7096
+ // No body on a DELETE, so the query string is the only way to name
7097
+ // an owner here — unlike the PUT, which reads either and prefers
7098
+ // the body.
7099
+ query: ownerNameQuery
7100
+ },
7101
+ responses: {
7102
+ 200: {
7103
+ description: "Deleted (or was already absent)",
7104
+ content: { "application/json": { schema: AnswersResponseSchema } }
7105
+ },
7106
+ 403: {
7107
+ description: "Forbidden",
7108
+ content: { "application/json": { schema: ErrorResponseSchema } }
7109
+ },
7110
+ 404: {
7111
+ description: "No such owner name",
7112
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7113
+ },
7114
+ 409: {
7115
+ description: "That owner name has never signed in",
7116
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7117
+ },
7118
+ 503: {
7119
+ description: "Identity could not be resolved right now — retry",
7120
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7121
+ }
7122
+ }
7123
+ }),
7124
+ async (c) => {
7125
+ const { ownerName } = c.req.valid("query");
7126
+ const who = await effectiveUserId(c, ownerName);
7127
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
7128
+ const userId = who.userId;
7129
+ const { key } = c.req.valid("param");
7130
+ const db = c.env.JOB_PLATFORM_DB;
7131
+ await db.prepare("DELETE FROM application_answers WHERE user_id = ? AND question_key = ?").bind(userId, key).run();
7132
+ const rows = await db.prepare(
7133
+ `SELECT question_key, question, answer, updated_at
7134
+ FROM application_answers WHERE user_id = ? ORDER BY updated_at DESC`
7135
+ ).bind(userId).all();
7136
+ return c.json({ success: true, data: { answers: rows.results } }, 200);
7137
+ }
7138
+ );
7139
+ app2.openapi(
7140
+ createRoute({
7141
+ method: "get",
7142
+ path: "/unanswered-questions",
7143
+ tags: ["Answers"],
7144
+ summary: "Questions the runner could not answer, most costly first",
7145
+ request: {
7146
+ query: ownerNameQuery
7147
+ },
7148
+ responses: {
7149
+ 200: {
7150
+ description: "The queue",
7151
+ content: { "application/json": { schema: UnansweredResponseSchema } }
7152
+ },
7153
+ 403: {
7154
+ description: "Forbidden",
7155
+ content: { "application/json": { schema: ErrorResponseSchema } }
7156
+ },
7157
+ 404: {
7158
+ description: "No such owner name",
7159
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7160
+ },
7161
+ 409: {
7162
+ description: "That owner name has never signed in",
7163
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7164
+ },
7165
+ 503: {
7166
+ description: "Identity could not be resolved right now — retry",
7167
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7168
+ }
7169
+ }
7170
+ }),
7171
+ async (c) => {
7172
+ const { ownerName } = c.req.valid("query");
7173
+ const who = await effectiveUserId(c, ownerName);
7174
+ if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
7175
+ const questions = await unansweredQuestions(c.env.JOB_PLATFORM_DB, who.userId);
7176
+ return c.json({ success: true, data: { questions } }, 200);
6879
7177
  }
6880
7178
  );
7179
+ }
7180
+ function registerOwnerRoutes(app2) {
7181
+ app2.post("/applications/:id/owner", gateAuthed);
6881
7182
  app2.openapi(
6882
7183
  createRoute({
6883
7184
  method: "post",
6884
- path: "/applications/{id}/approve",
7185
+ path: "/applications/{id}/owner",
6885
7186
  tags: ["Applications"],
6886
- summary: "Approve a filled application for submission (review-mode pause point)",
6887
- request: { params: z.object({ id: z.string() }) },
7187
+ summary: "Hand an application to another user, named by display name",
7188
+ request: {
7189
+ params: z.object({ id: z.string() }),
7190
+ body: { content: { "application/json": { schema: ReassignOwnerInputSchema } } }
7191
+ },
6888
7192
  responses: {
6889
7193
  200: {
6890
- description: "Approved — the runner will submit",
6891
- content: { "application/json": { schema: ApplicationResponseSchema } }
7194
+ description: "Reassigned",
7195
+ content: { "application/json": { schema: ReassignOwnerResponseSchema } }
6892
7196
  },
6893
7197
  403: {
6894
7198
  description: "Forbidden",
6895
7199
  content: { "application/json": { schema: ErrorResponseSchema } }
6896
7200
  },
7201
+ 400: {
7202
+ description: "The name was empty or otherwise unusable",
7203
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7204
+ },
6897
7205
  404: {
6898
- description: "Application not found",
6899
- content: { "application/json": { schema: ErrorResponseSchema } }
7206
+ description: "No such application, not yours, or no such name",
7207
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
6900
7208
  },
6901
7209
  409: {
6902
- description: "Not in 'filled', or filled without a fingerprint to bind to",
6903
- content: { "application/json": { schema: ErrorResponseSchema } }
7210
+ description: "That name has never signed in, so it has no userId to own rows",
7211
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
7212
+ },
7213
+ 503: {
7214
+ description: "Identity could not be resolved right now — retry",
7215
+ content: { "application/json": { schema: IdentityErrorResponseSchema } }
6904
7216
  }
6905
7217
  }
6906
7218
  }),
6907
7219
  async (c) => {
6908
- const userId = await maybeUserId(c);
6909
- if (!userId) return c.json(FORBIDDEN, 403);
7220
+ const callerId = await maybeUserId(c);
7221
+ if (!callerId) {
7222
+ return c.json(
7223
+ { success: false, error: "Forbidden", message: "Authentication required" },
7224
+ 403
7225
+ );
7226
+ }
6910
7227
  const { id } = c.req.valid("param");
7228
+ const { name } = c.req.valid("json");
6911
7229
  const db = c.env.JOB_PLATFORM_DB;
6912
- const existing = await db.prepare("SELECT * FROM applications WHERE id = ? AND user_id = ?").bind(id, userId).first();
6913
- if (!existing) {
7230
+ const isAdmin = tierAtLeast(c.get("authContext"), "admin");
7231
+ const row = await db.prepare("SELECT user_id, job_id FROM applications WHERE id = ?").bind(id).first();
7232
+ if (!row || row.user_id !== callerId && !isAdmin) {
6914
7233
  return c.json(
6915
7234
  {
6916
7235
  success: false,
@@ -6920,60 +7239,56 @@ function registerApplicationRoutes(app2) {
6920
7239
  404
6921
7240
  );
6922
7241
  }
6923
- if (existing.status !== "filled") {
6924
- recordEvent(c, {
6925
- level: "warn",
6926
- event: "application.approve_refused",
6927
- message: `${id}: is ${existing.status}, not filled`,
6928
- context: { application_id: id, user_id: userId, status: existing.status }
6929
- });
6930
- return c.json(
6931
- {
6932
- success: false,
6933
- error: "Conflict",
6934
- message: `Application '${id}' is '${existing.status}', not 'filled' — only a filled application can be approved`
6935
- },
6936
- 409
6937
- );
6938
- }
6939
- const fingerprint = parseEvidence(existing.evidence)?.fingerprint;
6940
- if (typeof fingerprint !== "string" || fingerprint.length === 0) {
6941
- recordEvent(c, {
6942
- level: "warn",
6943
- event: "application.approve_refused",
6944
- message: `${id}: filled without a fingerprint`,
6945
- context: { application_id: id, user_id: userId, status: existing.status }
6946
- });
7242
+ const resolved = await resolveOwnerName(
7243
+ c.env.JOB_PLATFORM_DB,
7244
+ c.env.EDGE,
7245
+ c.env.HADOKU_SERVICE_KEY ?? "",
7246
+ name,
7247
+ Date.now(),
7248
+ (label2, work) => runAfterResponse(c, label2, work)
7249
+ );
7250
+ if (isIdentityError(resolved)) {
7251
+ const status = [400, 404, 409, 503].includes(resolved.status) ? resolved.status : 503;
6947
7252
  return c.json(
6948
7253
  {
6949
7254
  success: false,
6950
- error: "Conflict",
6951
- message: `Application '${id}' was filled without a fingerprint, so there is nothing to bind this approval to — re-run the fill and approve the new screenshot`
7255
+ error: status === 503 ? "Unavailable" : status === 409 ? "Conflict" : "Not found",
7256
+ message: resolved.error,
7257
+ ...resolved.code ? { code: resolved.code } : {}
6952
7258
  },
6953
- 409
7259
+ status
6954
7260
  );
6955
7261
  }
6956
7262
  const now = (/* @__PURE__ */ new Date()).toISOString();
6957
- await db.prepare(
6958
- `UPDATE applications SET status = 'approved', approved_fingerprint = ?,
6959
- updated_at = ? WHERE id = ?`
6960
- ).bind(fingerprint, now, id).run();
7263
+ await db.batch([
7264
+ db.prepare("UPDATE applications SET user_id = ?, updated_at = ? WHERE id = ?").bind(resolved.userId, now, id),
7265
+ db.prepare(
7266
+ `INSERT OR REPLACE INTO job_states (job_id, user_id, state, notes, updated_at, variant_slug,
7267
+ priority, follow_up_at, contact_name, contact_email)
7268
+ SELECT job_id, ?, state, notes, ?, variant_slug,
7269
+ priority, follow_up_at, contact_name, contact_email
7270
+ FROM job_states WHERE job_id = ? AND user_id = ?`
7271
+ ).bind(resolved.userId, now, row.job_id, row.user_id)
7272
+ ]);
6961
7273
  recordEvent(c, {
6962
7274
  level: "info",
6963
- event: "application.approved",
6964
- message: `${id}: approved`,
6965
- context: { application_id: id, job_id: existing.job_id, user_id: userId }
7275
+ event: "application.handed_off",
7276
+ message: `${id}: to ${resolved.name}`,
7277
+ context: {
7278
+ application_id: id,
7279
+ job_id: row.job_id,
7280
+ from_user_id: row.user_id,
7281
+ to_user_id: resolved.userId
7282
+ }
6966
7283
  });
6967
7284
  return c.json(
6968
7285
  {
6969
7286
  success: true,
6970
7287
  data: {
6971
- application: toApplication({
6972
- ...existing,
6973
- status: "approved",
6974
- approved_fingerprint: fingerprint,
6975
- updated_at: now
6976
- })
7288
+ application_id: id,
7289
+ // The echo IS the point (R4): the caller sees which identity
7290
+ // they actually hit, for the one change they cannot undo alone.
7291
+ grantedTo: { name: resolved.name, tier: resolved.tier ?? null }
6977
7292
  }
6978
7293
  },
6979
7294
  200
@@ -7067,124 +7382,6 @@ function registerVerificationRoutes(app2) {
7067
7382
  return c.json({ success: true, data: { codes } }, 200);
7068
7383
  });
7069
7384
  }
7070
- const RESUME_PDF_URL = "https://hadoku.me/resume/api/resume.pdf";
7071
- function badRequest(message) {
7072
- return { success: false, error: "Bad request", message };
7073
- }
7074
- function validProfile(p) {
7075
- if (typeof p !== "object" || p === null || Array.isArray(p)) return false;
7076
- const o = p;
7077
- return typeof o.name === "string" && !!o.name.trim() && typeof o.email === "string";
7078
- }
7079
- const PROFILE_TEXT_LIMITS = {
7080
- work_authorization: 200,
7081
- desired_salary: 100,
7082
- notice_period: 100,
7083
- master_resume_text: 5e4
7084
- };
7085
- function profileProblem(p) {
7086
- for (const [key, max] of Object.entries(PROFILE_TEXT_LIMITS)) {
7087
- const v = p[key];
7088
- if (v === void 0 || v === null) continue;
7089
- if (typeof v !== "string") return `${key} must be a string`;
7090
- if (v.length > max) return `${key} is longer than ${max} characters`;
7091
- }
7092
- return null;
7093
- }
7094
- async function loadProfile(db, userId) {
7095
- const row = await db.prepare("SELECT profile, updated_at FROM applicant_profiles WHERE user_id = ?").bind(userId).first();
7096
- if (!row) return null;
7097
- try {
7098
- const parsed = JSON.parse(row.profile);
7099
- return validProfile(parsed) ? { profile: parsed, updated_at: row.updated_at } : null;
7100
- } catch {
7101
- return null;
7102
- }
7103
- }
7104
- function registerFillRoutes(app2) {
7105
- app2.get("/applicant-profile", gateAuthed);
7106
- app2.get("/applicant-profile", async (c) => {
7107
- const who = await effectiveUserId(c, c.req.query("ownerName"));
7108
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
7109
- const found = await loadProfile(c.env.JOB_PLATFORM_DB, who.userId);
7110
- return c.json(
7111
- {
7112
- success: true,
7113
- data: { profile: found?.profile ?? null, updated_at: found?.updated_at ?? null }
7114
- },
7115
- 200
7116
- );
7117
- });
7118
- app2.put("/applicant-profile", gateAuthed);
7119
- app2.put("/applicant-profile", async (c) => {
7120
- let body;
7121
- try {
7122
- body = await c.req.json();
7123
- } catch {
7124
- return c.json(badRequest("Body must be JSON"), 400);
7125
- }
7126
- const b = typeof body === "object" && body !== null ? body : {};
7127
- if (!validProfile(b.profile)) {
7128
- return c.json(badRequest("profile must be an object with a name and an email"), 400);
7129
- }
7130
- const problem = profileProblem(b.profile);
7131
- if (problem) return c.json(badRequest(problem), 400);
7132
- const who = await effectiveUserId(c, typeof b.ownerName === "string" ? b.ownerName : void 0);
7133
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
7134
- const now = (/* @__PURE__ */ new Date()).toISOString();
7135
- await c.env.JOB_PLATFORM_DB.prepare(
7136
- `INSERT INTO applicant_profiles (user_id, profile, updated_at) VALUES (?, ?, ?)
7137
- ON CONFLICT (user_id) DO UPDATE SET profile = excluded.profile, updated_at = excluded.updated_at`
7138
- ).bind(who.userId, JSON.stringify(b.profile), now).run();
7139
- return c.json({ success: true, data: { updated_at: now } }, 200);
7140
- });
7141
- app2.get("/jobs/:id/fill-packet", gateAuthed);
7142
- app2.get("/jobs/:id/fill-packet", async (c) => {
7143
- const id = c.req.param("id");
7144
- const who = await effectiveUserId(c, c.req.query("ownerName"));
7145
- if (isEffectiveUserError(who)) return c.json(who.error.body, who.error.status);
7146
- const db = c.env.JOB_PLATFORM_DB;
7147
- const job = await db.prepare("SELECT id, company, title, url FROM jobs WHERE id = ?").bind(id).first();
7148
- if (!job) {
7149
- return c.json(
7150
- { success: false, error: "Not found", message: `Job '${id}' not found` },
7151
- 404
7152
- );
7153
- }
7154
- const app_ = await db.prepare(
7155
- `SELECT id, status, variant_slug, evidence FROM applications
7156
- WHERE user_id = ? AND job_id = ?`
7157
- ).bind(who.userId, id).first();
7158
- const state = await db.prepare("SELECT variant_slug FROM job_states WHERE user_id = ? AND job_id = ?").bind(who.userId, id).first();
7159
- const slug2 = app_?.variant_slug || state?.variant_slug || "";
7160
- const evidence = parseEvidence(app_?.evidence ?? null) ?? {};
7161
- const answers = typeof evidence.answers === "object" && evidence.answers !== null ? evidence.answers : {};
7162
- const options = typeof evidence.options === "object" && evidence.options !== null ? evidence.options : {};
7163
- const multi = Array.isArray(evidence.multi) ? evidence.multi : [];
7164
- const standing = await db.prepare("SELECT question, answer FROM application_answers WHERE user_id = ?").bind(who.userId).all();
7165
- const profile = await loadProfile(db, who.userId);
7166
- return c.json(
7167
- {
7168
- success: true,
7169
- data: {
7170
- job: { ...job, url: publicUrl(job.url) },
7171
- application: app_ ? { id: app_.id, status: app_.status, variant_slug: slug2 } : null,
7172
- profile: profile?.profile ?? null,
7173
- // What the approved fill entered, keyed by the runner's normalised
7174
- // question — the primary source, because it is what was reviewed.
7175
- answers,
7176
- options,
7177
- multi,
7178
- // Every saved answer by its question, for anything the fill did
7179
- // not record (a field added since, a structured block).
7180
- standing: Object.fromEntries(standing.results.map((r) => [r.question, r.answer])),
7181
- resume_pdf_url: slug2 ? `${RESUME_PDF_URL}?v=${encodeURIComponent(slug2)}` : null
7182
- }
7183
- },
7184
- 200
7185
- );
7186
- });
7187
- }
7188
7385
  const ERRORS$2 = {
7189
7386
  403: {
7190
7387
  description: "Forbidden",