diff --git a/docs/agents/mail-stack.md b/docs/agents/mail-stack.md index a8388ba22c..f6fd01a587 100644 --- a/docs/agents/mail-stack.md +++ b/docs/agents/mail-stack.md @@ -43,28 +43,6 @@ the point: it is the tier that costs us nothing. See the `external` bullets belo ## Always true -- **Gmail keeps both directions inside hiring threads.** Incoming search excludes SENT and - DRAFT mail; thread expansion retains sent replies and discards drafts. Gmail's SENT label - identifies aliases; the connected primary address is a fallback. `emails.direction` is - `incoming` or `outgoing`, with To/Cc headers and thread ids exposed to inbox readers. - Sent messages start read and never enter employer classification, stage advancement, - employer-reply events, interview evidence or silence calculations. Hosted and external - messages retain their existing incoming defaults; this adds no sending transport. - Application mail views also show unlinked sent replies when their Gmail conversation - has one unambiguous linked incoming job, including links classified after sync. Explicit - attachments win; this display inference writes no link or employer activity. Recall - candidates and suggestion writes remain incoming-only, including after alias repair. -- **Sent discovery has its own cursor.** `gmail_connections.sent_sync_cursor` starts at zero: - the first successful pass expands stored Gmail threads to recover their sent history. - Later passes list SENT message/thread identifiers since the prior successful run (with a - 60-second overlap), fetching content only for known hiring threads. This catches replies - to old conversations without a new incoming anchor. The cursor records run-start time; - a transient message or thread failure preserves both cursors, and idempotent inserts - make retries safe. Permanently missing provider messages/threads are skipped. Reimports - refresh direction and recipient metadata; an old alias reply newly recognized as SENT - loses its employer classification, pending work and employer-reply event. Existing - application stages are not automatically rolled back: that would overwrite later user - decisions. Apply migration 0267 before deploying the readers. - **The fetch is scoped to hiring-SHAPED mail, not to ATS senders, and the inbox filters at DISPLAY.** `gmailsync.BuildQueryFor` admits mail from a curated ATS domain OR carrying one of the recognised application/interview phrasings, minus anything the connected address diff --git a/internal/api/apigen/oas_json_gen.go b/internal/api/apigen/oas_json_gen.go index 34e366181b..fcc7217b2f 100644 --- a/internal/api/apigen/oas_json_gen.go +++ b/internal/api/apigen/oas_json_gen.go @@ -39087,24 +39087,6 @@ func (s *InboxApplicationEmail) encodeFields(e *jx.Encoder) { e.FieldStart("source") e.Str(s.Source) } - { - if s.Direction.Set { - e.FieldStart("direction") - s.Direction.Encode(e) - } - } - { - if s.ToAddrs.Set { - e.FieldStart("to_addrs") - s.ToAddrs.Encode(e) - } - } - { - if s.CcAddrs.Set { - e.FieldStart("cc_addrs") - s.CcAddrs.Encode(e) - } - } { e.FieldStart("from_addr") e.Str(s.FromAddr) @@ -39139,19 +39121,16 @@ func (s *InboxApplicationEmail) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfInboxApplicationEmail = [12]string{ - 0: "id", - 1: "source", - 2: "direction", - 3: "to_addrs", - 4: "cc_addrs", - 5: "from_addr", - 6: "from_name", - 7: "subject", - 8: "status_signal", - 9: "link_source", - 10: "received_at", - 11: "read", +var jsonFieldsNameOfInboxApplicationEmail = [9]string{ + 0: "id", + 1: "source", + 2: "from_addr", + 3: "from_name", + 4: "subject", + 5: "status_signal", + 6: "link_source", + 7: "received_at", + 8: "read", } // Decode decodes InboxApplicationEmail from json. @@ -39187,38 +39166,8 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"source\"") } - case "direction": - if err := func() error { - s.Direction.Reset() - if err := s.Direction.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"direction\"") - } - case "to_addrs": - if err := func() error { - s.ToAddrs.Reset() - if err := s.ToAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"to_addrs\"") - } - case "cc_addrs": - if err := func() error { - s.CcAddrs.Reset() - if err := s.CcAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"cc_addrs\"") - } case "from_addr": - requiredBitSet[0] |= 1 << 5 + requiredBitSet[0] |= 1 << 2 if err := func() error { v, err := d.Str() s.FromAddr = string(v) @@ -39230,7 +39179,7 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_addr\"") } case "from_name": - requiredBitSet[0] |= 1 << 6 + requiredBitSet[0] |= 1 << 3 if err := func() error { v, err := d.Str() s.FromName = string(v) @@ -39242,7 +39191,7 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_name\"") } case "subject": - requiredBitSet[0] |= 1 << 7 + requiredBitSet[0] |= 1 << 4 if err := func() error { v, err := d.Str() s.Subject = string(v) @@ -39274,7 +39223,7 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"link_source\"") } case "received_at": - requiredBitSet[1] |= 1 << 2 + requiredBitSet[0] |= 1 << 7 if err := func() error { v, err := json.DecodeTimeFormat(d, "2006-01-02T15:04:05.999999999Z07:00") s.ReceivedAt = v @@ -39286,7 +39235,7 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"received_at\"") } case "read": - requiredBitSet[1] |= 1 << 3 + requiredBitSet[1] |= 1 << 0 if err := func() error { v, err := d.Bool() s.Read = bool(v) @@ -39307,8 +39256,8 @@ func (s *InboxApplicationEmail) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [2]uint8{ - 0b11100011, - 0b00001100, + 0b10011111, + 0b00000001, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -39375,30 +39324,6 @@ func (s *InboxEmail) encodeFields(e *jx.Encoder) { e.FieldStart("external_id") e.Str(s.ExternalID) } - { - if s.Direction.Set { - e.FieldStart("direction") - s.Direction.Encode(e) - } - } - { - if s.ToAddrs.Set { - e.FieldStart("to_addrs") - s.ToAddrs.Encode(e) - } - } - { - if s.CcAddrs.Set { - e.FieldStart("cc_addrs") - s.CcAddrs.Encode(e) - } - } - { - if s.ThreadID.Set { - e.FieldStart("thread_id") - s.ThreadID.Encode(e) - } - } { e.FieldStart("from_addr") e.Str(s.FromAddr) @@ -39465,27 +39390,23 @@ func (s *InboxEmail) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfInboxEmail = [20]string{ +var jsonFieldsNameOfInboxEmail = [16]string{ 0: "id", 1: "source", 2: "external_id", - 3: "direction", - 4: "to_addrs", - 5: "cc_addrs", - 6: "thread_id", - 7: "from_addr", - 8: "from_name", - 9: "subject", - 10: "body_text", - 11: "body_html", - 12: "received_at", - 13: "read", - 14: "status_signal", - 15: "link_source", - 16: "linked_slug", - 17: "linked_company", - 18: "suggested_slug", - 19: "suggested_company", + 3: "from_addr", + 4: "from_name", + 5: "subject", + 6: "body_text", + 7: "body_html", + 8: "received_at", + 9: "read", + 10: "status_signal", + 11: "link_source", + 12: "linked_slug", + 13: "linked_company", + 14: "suggested_slug", + 15: "suggested_company", } // Decode decodes InboxEmail from json. @@ -39493,7 +39414,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { if s == nil { return errors.New("invalid: unable to decode InboxEmail to nil") } - var requiredBitSet [3]uint8 + var requiredBitSet [2]uint8 if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { @@ -39533,48 +39454,8 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"external_id\"") } - case "direction": - if err := func() error { - s.Direction.Reset() - if err := s.Direction.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"direction\"") - } - case "to_addrs": - if err := func() error { - s.ToAddrs.Reset() - if err := s.ToAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"to_addrs\"") - } - case "cc_addrs": - if err := func() error { - s.CcAddrs.Reset() - if err := s.CcAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"cc_addrs\"") - } - case "thread_id": - if err := func() error { - s.ThreadID.Reset() - if err := s.ThreadID.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"thread_id\"") - } case "from_addr": - requiredBitSet[0] |= 1 << 7 + requiredBitSet[0] |= 1 << 3 if err := func() error { v, err := d.Str() s.FromAddr = string(v) @@ -39586,7 +39467,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_addr\"") } case "from_name": - requiredBitSet[1] |= 1 << 0 + requiredBitSet[0] |= 1 << 4 if err := func() error { v, err := d.Str() s.FromName = string(v) @@ -39598,7 +39479,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_name\"") } case "subject": - requiredBitSet[1] |= 1 << 1 + requiredBitSet[0] |= 1 << 5 if err := func() error { v, err := d.Str() s.Subject = string(v) @@ -39610,7 +39491,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"subject\"") } case "body_text": - requiredBitSet[1] |= 1 << 2 + requiredBitSet[0] |= 1 << 6 if err := func() error { v, err := d.Str() s.BodyText = string(v) @@ -39622,7 +39503,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"body_text\"") } case "body_html": - requiredBitSet[1] |= 1 << 3 + requiredBitSet[0] |= 1 << 7 if err := func() error { v, err := d.Str() s.BodyHTML = string(v) @@ -39634,7 +39515,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"body_html\"") } case "received_at": - requiredBitSet[1] |= 1 << 4 + requiredBitSet[1] |= 1 << 0 if err := func() error { v, err := json.DecodeTimeFormat(d, "2006-01-02T15:04:05.999999999Z07:00") s.ReceivedAt = v @@ -39646,7 +39527,7 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"received_at\"") } case "read": - requiredBitSet[1] |= 1 << 5 + requiredBitSet[1] |= 1 << 1 if err := func() error { v, err := d.Bool() s.Read = bool(v) @@ -39726,10 +39607,9 @@ func (s *InboxEmail) Decode(d *jx.Decoder) error { } // Validate required fields. var failures []validate.FieldError - for i, mask := range [3]uint8{ - 0b10000111, - 0b00111111, - 0b00000000, + for i, mask := range [2]uint8{ + 0b11111111, + 0b00000011, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -40068,30 +39948,6 @@ func (s *InboxMessage) encodeFields(e *jx.Encoder) { e.FieldStart("external_id") e.Str(s.ExternalID) } - { - if s.Direction.Set { - e.FieldStart("direction") - s.Direction.Encode(e) - } - } - { - if s.ToAddrs.Set { - e.FieldStart("to_addrs") - s.ToAddrs.Encode(e) - } - } - { - if s.CcAddrs.Set { - e.FieldStart("cc_addrs") - s.CcAddrs.Encode(e) - } - } - { - if s.ThreadID.Set { - e.FieldStart("thread_id") - s.ThreadID.Encode(e) - } - } { e.FieldStart("from_addr") e.Str(s.FromAddr) @@ -40160,27 +40016,23 @@ func (s *InboxMessage) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfInboxMessage = [20]string{ +var jsonFieldsNameOfInboxMessage = [16]string{ 0: "id", 1: "source", 2: "external_id", - 3: "direction", - 4: "to_addrs", - 5: "cc_addrs", - 6: "thread_id", - 7: "from_addr", - 8: "from_name", - 9: "subject", - 10: "snippet", - 11: "body_text", - 12: "received_at", - 13: "read", - 14: "status_signal", - 15: "link_source", - 16: "linked_slug", - 17: "linked_company", - 18: "suggested_slug", - 19: "suggested_company", + 3: "from_addr", + 4: "from_name", + 5: "subject", + 6: "snippet", + 7: "body_text", + 8: "received_at", + 9: "read", + 10: "status_signal", + 11: "link_source", + 12: "linked_slug", + 13: "linked_company", + 14: "suggested_slug", + 15: "suggested_company", } // Decode decodes InboxMessage from json. @@ -40188,7 +40040,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { if s == nil { return errors.New("invalid: unable to decode InboxMessage to nil") } - var requiredBitSet [3]uint8 + var requiredBitSet [2]uint8 if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { @@ -40228,48 +40080,8 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"external_id\"") } - case "direction": - if err := func() error { - s.Direction.Reset() - if err := s.Direction.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"direction\"") - } - case "to_addrs": - if err := func() error { - s.ToAddrs.Reset() - if err := s.ToAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"to_addrs\"") - } - case "cc_addrs": - if err := func() error { - s.CcAddrs.Reset() - if err := s.CcAddrs.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"cc_addrs\"") - } - case "thread_id": - if err := func() error { - s.ThreadID.Reset() - if err := s.ThreadID.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"thread_id\"") - } case "from_addr": - requiredBitSet[0] |= 1 << 7 + requiredBitSet[0] |= 1 << 3 if err := func() error { v, err := d.Str() s.FromAddr = string(v) @@ -40281,7 +40093,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_addr\"") } case "from_name": - requiredBitSet[1] |= 1 << 0 + requiredBitSet[0] |= 1 << 4 if err := func() error { v, err := d.Str() s.FromName = string(v) @@ -40293,7 +40105,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"from_name\"") } case "subject": - requiredBitSet[1] |= 1 << 1 + requiredBitSet[0] |= 1 << 5 if err := func() error { v, err := d.Str() s.Subject = string(v) @@ -40305,7 +40117,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"subject\"") } case "snippet": - requiredBitSet[1] |= 1 << 2 + requiredBitSet[0] |= 1 << 6 if err := func() error { v, err := d.Str() s.Snippet = string(v) @@ -40327,7 +40139,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"body_text\"") } case "received_at": - requiredBitSet[1] |= 1 << 4 + requiredBitSet[1] |= 1 << 0 if err := func() error { v, err := json.DecodeTimeFormat(d, "2006-01-02T15:04:05.999999999Z07:00") s.ReceivedAt = v @@ -40339,7 +40151,7 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"received_at\"") } case "read": - requiredBitSet[1] |= 1 << 5 + requiredBitSet[1] |= 1 << 1 if err := func() error { v, err := d.Bool() s.Read = bool(v) @@ -40419,10 +40231,9 @@ func (s *InboxMessage) Decode(d *jx.Decoder) error { } // Validate required fields. var failures []validate.FieldError - for i, mask := range [3]uint8{ - 0b10000111, - 0b00110111, - 0b00000000, + for i, mask := range [2]uint8{ + 0b01111111, + 0b00000011, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. diff --git a/internal/api/apigen/oas_schemas_gen.go b/internal/api/apigen/oas_schemas_gen.go index 81039498b4..0af0ae245f 100644 --- a/internal/api/apigen/oas_schemas_gen.go +++ b/internal/api/apigen/oas_schemas_gen.go @@ -11923,9 +11923,6 @@ func (s *InboxApplicationDetail) SetAutoApply(val OptAutoApplyReviewInfo) { type InboxApplicationEmail struct { ID int64 `json:"id"` Source string `json:"source"` - Direction OptString `json:"direction"` - ToAddrs OptString `json:"to_addrs"` - CcAddrs OptString `json:"cc_addrs"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` Subject string `json:"subject"` @@ -11945,21 +11942,6 @@ func (s *InboxApplicationEmail) GetSource() string { return s.Source } -// GetDirection returns the value of Direction. -func (s *InboxApplicationEmail) GetDirection() OptString { - return s.Direction -} - -// GetToAddrs returns the value of ToAddrs. -func (s *InboxApplicationEmail) GetToAddrs() OptString { - return s.ToAddrs -} - -// GetCcAddrs returns the value of CcAddrs. -func (s *InboxApplicationEmail) GetCcAddrs() OptString { - return s.CcAddrs -} - // GetFromAddr returns the value of FromAddr. func (s *InboxApplicationEmail) GetFromAddr() string { return s.FromAddr @@ -12005,21 +11987,6 @@ func (s *InboxApplicationEmail) SetSource(val string) { s.Source = val } -// SetDirection sets the value of Direction. -func (s *InboxApplicationEmail) SetDirection(val OptString) { - s.Direction = val -} - -// SetToAddrs sets the value of ToAddrs. -func (s *InboxApplicationEmail) SetToAddrs(val OptString) { - s.ToAddrs = val -} - -// SetCcAddrs sets the value of CcAddrs. -func (s *InboxApplicationEmail) SetCcAddrs(val OptString) { - s.CcAddrs = val -} - // SetFromAddr sets the value of FromAddr. func (s *InboxApplicationEmail) SetFromAddr(val string) { s.FromAddr = val @@ -12061,10 +12028,6 @@ type InboxEmail struct { ID int64 `json:"id"` Source string `json:"source"` ExternalID string `json:"external_id"` - Direction OptString `json:"direction"` - ToAddrs OptString `json:"to_addrs"` - CcAddrs OptString `json:"cc_addrs"` - ThreadID OptString `json:"thread_id"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` Subject string `json:"subject"` @@ -12095,26 +12058,6 @@ func (s *InboxEmail) GetExternalID() string { return s.ExternalID } -// GetDirection returns the value of Direction. -func (s *InboxEmail) GetDirection() OptString { - return s.Direction -} - -// GetToAddrs returns the value of ToAddrs. -func (s *InboxEmail) GetToAddrs() OptString { - return s.ToAddrs -} - -// GetCcAddrs returns the value of CcAddrs. -func (s *InboxEmail) GetCcAddrs() OptString { - return s.CcAddrs -} - -// GetThreadID returns the value of ThreadID. -func (s *InboxEmail) GetThreadID() OptString { - return s.ThreadID -} - // GetFromAddr returns the value of FromAddr. func (s *InboxEmail) GetFromAddr() string { return s.FromAddr @@ -12195,26 +12138,6 @@ func (s *InboxEmail) SetExternalID(val string) { s.ExternalID = val } -// SetDirection sets the value of Direction. -func (s *InboxEmail) SetDirection(val OptString) { - s.Direction = val -} - -// SetToAddrs sets the value of ToAddrs. -func (s *InboxEmail) SetToAddrs(val OptString) { - s.ToAddrs = val -} - -// SetCcAddrs sets the value of CcAddrs. -func (s *InboxEmail) SetCcAddrs(val OptString) { - s.CcAddrs = val -} - -// SetThreadID sets the value of ThreadID. -func (s *InboxEmail) SetThreadID(val OptString) { - s.ThreadID = val -} - // SetFromAddr sets the value of FromAddr. func (s *InboxEmail) SetFromAddr(val string) { s.FromAddr = val @@ -12343,10 +12266,6 @@ type InboxMessage struct { ID int64 `json:"id"` Source string `json:"source"` ExternalID string `json:"external_id"` - Direction OptString `json:"direction"` - ToAddrs OptString `json:"to_addrs"` - CcAddrs OptString `json:"cc_addrs"` - ThreadID OptString `json:"thread_id"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` Subject string `json:"subject"` @@ -12377,26 +12296,6 @@ func (s *InboxMessage) GetExternalID() string { return s.ExternalID } -// GetDirection returns the value of Direction. -func (s *InboxMessage) GetDirection() OptString { - return s.Direction -} - -// GetToAddrs returns the value of ToAddrs. -func (s *InboxMessage) GetToAddrs() OptString { - return s.ToAddrs -} - -// GetCcAddrs returns the value of CcAddrs. -func (s *InboxMessage) GetCcAddrs() OptString { - return s.CcAddrs -} - -// GetThreadID returns the value of ThreadID. -func (s *InboxMessage) GetThreadID() OptString { - return s.ThreadID -} - // GetFromAddr returns the value of FromAddr. func (s *InboxMessage) GetFromAddr() string { return s.FromAddr @@ -12477,26 +12376,6 @@ func (s *InboxMessage) SetExternalID(val string) { s.ExternalID = val } -// SetDirection sets the value of Direction. -func (s *InboxMessage) SetDirection(val OptString) { - s.Direction = val -} - -// SetToAddrs sets the value of ToAddrs. -func (s *InboxMessage) SetToAddrs(val OptString) { - s.ToAddrs = val -} - -// SetCcAddrs sets the value of CcAddrs. -func (s *InboxMessage) SetCcAddrs(val OptString) { - s.CcAddrs = val -} - -// SetThreadID sets the value of ThreadID. -func (s *InboxMessage) SetThreadID(val OptString) { - s.ThreadID = val -} - // SetFromAddr sets the value of FromAddr. func (s *InboxMessage) SetFromAddr(val string) { s.FromAddr = val diff --git a/internal/api/handler/assistant_inbox_tools.go b/internal/api/handler/assistant_inbox_tools.go index 2a5f2f22df..125472707e 100644 --- a/internal/api/handler/assistant_inbox_tools.go +++ b/internal/api/handler/assistant_inbox_tools.go @@ -86,10 +86,6 @@ func (h *assistantHandlers) inboxOverviewTool() assistant.Tool { type assistantMailMessage struct { ID int64 `json:"id"` Source string `json:"source"` - Direction string `json:"direction"` - ThreadID string `json:"thread_id,omitempty"` - ToAddrs string `json:"to_addrs,omitempty"` - CcAddrs string `json:"cc_addrs,omitempty"` From string `json:"from"` Subject string `json:"subject"` ReceivedAt string `json:"received_at"` @@ -114,7 +110,7 @@ func mailMessageView(m inbox.Message, withBody bool) assistantMailMessage { from = fmt.Sprintf("%s <%s>", m.FromName, m.FromAddr) } out := assistantMailMessage{ - ID: m.ID, Source: m.Source, From: from, Subject: m.Subject, Direction: m.Direction, ThreadID: m.ThreadID, ToAddrs: m.ToAddrs, CcAddrs: m.CcAddrs, + ID: m.ID, Source: m.Source, From: from, Subject: m.Subject, ReceivedAt: m.ReceivedAt.Format(time.RFC3339), Read: m.Read, Label: m.StatusSignal, LinkState: m.LinkState, LinkedSlug: m.LinkedSlug, LinkedTo: m.LinkedCompany, SuggestedFor: m.SuggestedSlug, diff --git a/internal/api/handler/followup.go b/internal/api/handler/followup.go index c6a3946a18..2da3db00ab 100644 --- a/internal/api/handler/followup.go +++ b/internal/api/handler/followup.go @@ -88,15 +88,10 @@ func (h *inboxHandlers) newestSender(ctx context.Context, userID, jobID int64) ( rows, err := h.queries.ListJobEmails(ctx, db.ListJobEmailsParams{ UserID: userID, JobID: pgtype.Int8{Int64: jobID, Valid: true}, }) - if err != nil { + if err != nil || len(rows) == 0 { return "", "" } - for _, row := range rows { - if row.Direction == "incoming" { - return row.FromAddr, row.FromName - } - } - return "", "" + return rows[0].FromAddr, rows[0].FromName } // cachedStrength reads one concrete strength from the cached fit analysis — text the analysis diff --git a/internal/api/handler/followup_integration_test.go b/internal/api/handler/followup_integration_test.go index b573e5afef..d8888d0f41 100644 --- a/internal/api/handler/followup_integration_test.go +++ b/internal/api/handler/followup_integration_test.go @@ -88,12 +88,6 @@ func TestFollowUpDraft_PrefillsTheRecipientFromLinkedMail(t *testing.T) { t.Fatalf("seed mail: %v", err) } - if _, err := f.pool.Exec(context.Background(), - `INSERT INTO emails (user_id,external_id,thread_id,from_addr,received_at,source,job_id,direction) - VALUES ($1,'fu-sent','t-1','fu-replied@example.test',now(),'gmail',$2,'outgoing')`, f.userID, jid); err != nil { - t.Fatal(err) - } - status, body := f.callKey(fiber.MethodGet, "/api/v1/me/tracking/followup-replied/followup", nil) if status != fiber.StatusOK { diff --git a/internal/api/handler/gmail.go b/internal/api/handler/gmail.go index 7fe3488e9f..77bbaf9e7d 100644 --- a/internal/api/handler/gmail.go +++ b/internal/api/handler/gmail.go @@ -434,7 +434,7 @@ func (h *inboxHandlers) SyncGmail(ctx context.Context) (*apigen.SyncGmailOK, err worker := gmailsync.NewWorker(gmailStore, h.gmailCipher, h.gmailConnector.ReaderFactory()).WithLearnedDomains(gmailStore) // Background context: the sync outlives this request. go worker.SyncUser(context.Background(), gmailsync.Connection{ - UserID: conn.UserID, Email: conn.Email, Cursor: conn.SyncCursor, SentCursor: conn.SentSyncCursor, + UserID: conn.UserID, Email: conn.Email, Cursor: conn.SyncCursor, }) return &apigen.SyncGmailOK{Data: apigen.GmailSyncStarted{Started: true}}, nil } diff --git a/internal/api/handler/inbox.go b/internal/api/handler/inbox.go index bead9bacc9..8d6a626bef 100644 --- a/internal/api/handler/inbox.go +++ b/internal/api/handler/inbox.go @@ -45,8 +45,7 @@ func emailPathID(raw string) (int64, error) { // internal raw-MIME pointer for hosted mail) is deliberately not exposed. func bodyOf(m inbox.Message) apigen.InboxEmail { return apigen.InboxEmail{ - ID: m.ID, Source: m.Source, ExternalID: m.ExternalID, Direction: optString(m.Direction), - ThreadID: optString(m.ThreadID), ToAddrs: optString(m.ToAddrs), CcAddrs: optString(m.CcAddrs), + ID: m.ID, Source: m.Source, ExternalID: m.ExternalID, FromAddr: m.FromAddr, FromName: m.FromName, Subject: m.Subject, BodyText: m.BodyText, BodyHTML: m.BodyHTML, ReceivedAt: m.ReceivedAt, Read: m.Read, @@ -115,8 +114,7 @@ func (h *inboxHandlers) GetInbox(ctx context.Context, _ apigen.GetInboxParams) ( out := make([]apigen.InboxMessage, 0, len(page.Messages)) for _, m := range page.Messages { out = append(out, apigen.InboxMessage{ - ID: m.ID, Source: m.Source, ExternalID: m.ExternalID, Direction: optString(m.Direction), - ThreadID: optString(m.ThreadID), ToAddrs: optString(m.ToAddrs), CcAddrs: optString(m.CcAddrs), + ID: m.ID, Source: m.Source, ExternalID: m.ExternalID, FromAddr: m.FromAddr, FromName: m.FromName, Subject: m.Subject, Snippet: m.Snippet, BodyText: optString(m.BodyText), ReceivedAt: m.ReceivedAt, Read: m.Read, diff --git a/internal/api/handler/inbox_linking.go b/internal/api/handler/inbox_linking.go index 0054025e0d..b2ecd03e80 100644 --- a/internal/api/handler/inbox_linking.go +++ b/internal/api/handler/inbox_linking.go @@ -55,8 +55,7 @@ func (h *inboxHandlers) GetTrackedApplication(ctx context.Context, params apigen forSuggestion := make([]jobtracking.SuggestionEmail, 0, len(rows)) for _, r := range rows { emails = append(emails, apigen.InboxApplicationEmail{ - ID: r.ID, Source: r.Source, Direction: optString(r.Direction), - ToAddrs: optString(r.ToAddrs), CcAddrs: optString(r.CcAddrs), FromAddr: r.FromAddr, FromName: r.FromName, + ID: r.ID, Source: r.Source, FromAddr: r.FromAddr, FromName: r.FromName, Subject: r.Subject, StatusSignal: optString(pgStr(r.StatusSignal)), LinkSource: optString(pgStr(r.LinkSource)), ReceivedAt: r.ReceivedAt.Time, Read: r.Read, }) diff --git a/internal/api/handler/inbox_outgoing_test.go b/internal/api/handler/inbox_outgoing_test.go deleted file mode 100644 index 153b8092bc..0000000000 --- a/internal/api/handler/inbox_outgoing_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package handler - -import ( - "testing" - - "github.com/strelov1/freehire/internal/application/inbox" -) - -func TestOutgoingMessageReadersKeepConversationMetadata(t *testing.T) { - m := inbox.Message{ID: 7, Source: "gmail", Direction: "outgoing", ThreadID: "thread", ToAddrs: "hr@example.test", CcAddrs: "team@example.test"} - body := bodyOf(m) - if body.Direction.Value != m.Direction || body.ThreadID.Value != m.ThreadID || body.ToAddrs.Value != m.ToAddrs || body.CcAddrs.Value != m.CcAddrs { - t.Fatalf("HTTP reader lost outgoing metadata: %+v", body) - } - agent := mailMessageView(m, false) - if agent.Direction != m.Direction || agent.ThreadID != m.ThreadID || agent.ToAddrs != m.ToAddrs || agent.CcAddrs != m.CcAddrs { - t.Fatalf("assistant reader lost outgoing metadata: %+v", agent) - } -} diff --git a/internal/application/gmailsync/dbstore.go b/internal/application/gmailsync/dbstore.go index 5f1428c26d..ef7da1d1ee 100644 --- a/internal/application/gmailsync/dbstore.go +++ b/internal/application/gmailsync/dbstore.go @@ -23,7 +23,7 @@ func (s *DBStore) ListConnected(ctx context.Context) ([]Connection, error) { } out := make([]Connection, 0, len(rows)) for _, r := range rows { - out = append(out, Connection{UserID: r.UserID, Email: r.Email, Cursor: r.SyncCursor, SentCursor: r.SentSyncCursor}) + out = append(out, Connection{UserID: r.UserID, Email: r.Email, Cursor: r.SyncCursor}) } return out, nil } @@ -38,7 +38,6 @@ func (s *DBStore) RefreshToken(ctx context.Context, userID int64) (string, error func (s *DBStore) UpsertEmail(ctx context.Context, e StoredEmail) error { return s.q.UpsertEmail(ctx, db.UpsertEmailParams{ - Direction: e.Message.Direction, ToAddrs: e.Message.ToAddrs, CcAddrs: e.Message.CcAddrs, UserID: e.UserID, ExternalID: e.Message.ID, ThreadID: e.Message.ThreadID, @@ -52,8 +51,8 @@ func (s *DBStore) UpsertEmail(ctx context.Context, e StoredEmail) error { }) } -func (s *DBStore) SetSynced(ctx context.Context, userID, cursorUnix, sentCursor int64) error { - return s.q.SetGmailSynced(ctx, db.SetGmailSyncedParams{UserID: userID, SyncCursor: cursorUnix, SentSyncCursor: sentCursor}) +func (s *DBStore) SetSynced(ctx context.Context, userID, cursorUnix int64) error { + return s.q.SetGmailSynced(ctx, db.SetGmailSyncedParams{UserID: userID, SyncCursor: cursorUnix}) } func (s *DBStore) SetNeedsReconsent(ctx context.Context, userID int64) error { @@ -81,7 +80,3 @@ func (s *DBStore) Promoted(ctx context.Context) ([]string, error) { MaxOtherShare: MaxOtherShare, }) } - -func (s *DBStore) ListThreadIDs(ctx context.Context, userID int64) ([]string, error) { - return s.q.ListGmailThreadIDs(ctx, userID) -} diff --git a/internal/application/gmailsync/gmailapi.go b/internal/application/gmailsync/gmailapi.go index 4ed2e2abfd..0769196da2 100644 --- a/internal/application/gmailsync/gmailapi.go +++ b/internal/application/gmailsync/gmailapi.go @@ -14,7 +14,6 @@ import ( "time" "github.com/strelov1/freehire/internal/application/ical" - "github.com/strelov1/freehire/internal/platform/mailmeta" ) const gmailBaseURL = "https://gmail.googleapis.com/gmail/v1/users/me" @@ -36,30 +35,16 @@ func NewAPIReader(client *http.Client, learned []string) GmailReader { // ListATSMessageIDs pages through the ATS-scoped search, returning all matching ids. func (r *apiReader) ListATSMessageIDs(ctx context.Context, selfAddr string, afterUnix int64) ([]string, error) { q := BuildQueryFor(selfAddr, afterUnix, r.learned) - refs, err := r.listMessages(ctx, q) - ids := make([]string, 0, len(refs)) - for _, ref := range refs { - ids = append(ids, ref.ID) - } - return ids, err -} - -func (r *apiReader) ListSentMessages(ctx context.Context, afterUnix int64) ([]MessageRef, error) { - return r.listMessages(ctx, fmt.Sprintf("in:sent after:%d", max(0, afterUnix-60))) -} - -func (r *apiReader) listMessages(ctx context.Context, query string) ([]MessageRef, error) { - var refs []MessageRef + var ids []string pageToken := "" for { - u := fmt.Sprintf("%s/messages?maxResults=100&q=%s", gmailBaseURL, url.QueryEscape(query)) + u := fmt.Sprintf("%s/messages?maxResults=100&q=%s", gmailBaseURL, url.QueryEscape(q)) if pageToken != "" { u += "&pageToken=" + url.QueryEscape(pageToken) } var page struct { Messages []struct { - ID string `json:"id"` - ThreadID string `json:"threadId"` + ID string `json:"id"` } `json:"messages"` NextPageToken string `json:"nextPageToken"` } @@ -67,10 +52,10 @@ func (r *apiReader) listMessages(ctx context.Context, query string) ([]MessageRe return nil, err } for _, m := range page.Messages { - refs = append(refs, MessageRef{ID: m.ID, ThreadID: m.ThreadID}) + ids = append(ids, m.ID) } if page.NextPageToken == "" { - return refs, nil + return ids, nil } pageToken = page.NextPageToken } @@ -154,7 +139,6 @@ type gmailHeader struct { type gmailMessage struct { ID string `json:"id"` - Labels []string `json:"labelIds"` ThreadID string `json:"threadId"` InternalDate string `json:"internalDate"` Payload gmailPart `json:"payload"` @@ -167,18 +151,7 @@ func parseMessage(raw []byte) (Message, error) { if err := json.Unmarshal(raw, &gm); err != nil { return Message{}, fmt.Errorf("gmail: decode message: %w", err) } - m := Message{ID: gm.ID, ThreadID: gm.ThreadID, Direction: DirectionIncoming} - for _, label := range gm.Labels { - if label == "SENT" { - m.Direction = DirectionOutgoing - } - if label == "DRAFT" { - m.Draft = true - } - } - m.SystemNotification = headerValue(gm.Payload.Headers, mailmeta.NotificationHeader) == mailmeta.InboxDigest && headerValue(gm.Payload.Headers, "Auto-Submitted") == "auto-generated" - m.ToAddrs = headerValue(gm.Payload.Headers, "To") - m.CcAddrs = headerValue(gm.Payload.Headers, "Cc") + m := Message{ID: gm.ID, ThreadID: gm.ThreadID} if ms, err := strconv.ParseInt(gm.InternalDate, 10, 64); err == nil { m.ReceivedAt = time.UnixMilli(ms) diff --git a/internal/application/gmailsync/gmailapi_list_test.go b/internal/application/gmailsync/gmailapi_list_test.go new file mode 100644 index 0000000000..eefcaf0b3b --- /dev/null +++ b/internal/application/gmailsync/gmailapi_list_test.go @@ -0,0 +1,38 @@ +package gmailsync + +import ( + "context" + "io" + "net/http" + "slices" + "strings" + "testing" +) + +// pagedGmail answers the message search with two pages, keyed by the page token. +type pagedGmail struct{ tokens []string } + +func (p *pagedGmail) RoundTrip(req *http.Request) (*http.Response, error) { + token := req.URL.Query().Get("pageToken") + p.tokens = append(p.tokens, token) + body := `{"messages":[{"id":"a"},{"id":"b"}],"nextPageToken":"p2"}` + if token == "p2" { + body = `{"messages":[{"id":"c"}]}` + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil +} + +func TestListATSMessageIDsFollowsEveryPage(t *testing.T) { + gmail := &pagedGmail{} + r := &apiReader{client: &http.Client{Transport: gmail}} + ids, err := r.ListATSMessageIDs(context.Background(), "me@example.test", 0) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(ids, []string{"a", "b", "c"}) { + t.Fatalf("ids = %v, want [a b c]", ids) + } + if !slices.Equal(gmail.tokens, []string{"", "p2"}) { + t.Fatalf("page tokens = %v, want first page then p2", gmail.tokens) + } +} diff --git a/internal/application/gmailsync/outgoing_test.go b/internal/application/gmailsync/outgoing_test.go deleted file mode 100644 index 8fb2a00b2d..0000000000 --- a/internal/application/gmailsync/outgoing_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package gmailsync - -import ( - "context" - "errors" - "strings" - "testing" - "time" -) - -func TestParseSentAlias(t *testing.T) { - msg, err := parseMessage([]byte(`{"id":"reply","threadId":"hiring","labelIds":["SENT"],"payload":{"headers":[{"name":"From","value":"Alias "},{"name":"To","value":"Recruiter "},{"name":"Cc","value":"team@example.test"}]}}`)) - if err != nil { - t.Fatal(err) - } - if msg.Direction != DirectionOutgoing || msg.ToAddrs != "Recruiter " || msg.CcAddrs != "team@example.test" { - t.Fatalf("sent message: %+v", msg) - } -} - -func TestSentReplyInOldThread(t *testing.T) { - for _, first := range []bool{true, false} { - t.Run(map[bool]string{true: "backfill", false: "incremental"}[first], func(t *testing.T) { - c := testCipher(t) - enc, _ := c.Encrypt("refresh") - cursor := int64(1_700_000_100) - sentCursor := cursor - if first { - sentCursor = 0 - } - store := &fakeStore{conns: []Connection{{UserID: 7, Cursor: cursor, SentCursor: sentCursor}}, encToken: enc, knownThreads: []string{"old"}} - reader := &fakeReader{ - byID: map[string]Message{"sent": {ID: "sent", ThreadID: "old", Direction: DirectionOutgoing, FromAddr: "alias@example.test", ReceivedAt: time.Unix(cursor+100, 0)}}, - threads: map[string][]string{"old": {"sent"}}, - sent: []MessageRef{{ID: "sent", ThreadID: "old"}, {ID: "personal", ThreadID: "private"}}, - getErrIDs: map[string]error{"personal": errors.New("unrelated body must never be fetched")}, - } - w := NewWorker(store, c, func(context.Context, string, []string) GmailReader { return reader }) - stats, err := w.RunOnce(context.Background()) - if err != nil { - t.Fatal(err) - } - if stats.Synced != 1 || len(store.upserted) != 1 || store.upserted[0].Message.ID != "sent" { - t.Fatalf("stats=%+v stored=%+v", stats, store.upserted) - } - if store.syncedCursor != cursor { - t.Fatalf("sent reply moved incoming cursor: %d", store.syncedCursor) - } - if store.syncedSent <= sentCursor { - t.Fatalf("sent cursor did not advance: %d", store.syncedSent) - } - }) - } -} - -func TestSentFailurePreservesCursors(t *testing.T) { - c := testCipher(t) - enc, _ := c.Encrypt("refresh") - store := &fakeStore{conns: []Connection{{UserID: 7, Cursor: 50, SentCursor: 60}}, encToken: enc} - reader := &fakeReader{sentErr: errors.New("temporary outage")} - w := NewWorker(store, c, func(context.Context, string, []string) GmailReader { return reader }) - stats, err := w.RunOnce(context.Background()) - if err != nil { - t.Fatal(err) - } - if stats.Failed != 1 || store.syncedCursor != 50 || store.syncedSent != 60 { - t.Fatalf("stats=%+v cursors=%d/%d", stats, store.syncedCursor, store.syncedSent) - } -} - -func TestDraftInHiringThreadIsNotStored(t *testing.T) { - c := testCipher(t) - enc, _ := c.Encrypt("refresh") - store := &fakeStore{conns: []Connection{{UserID: 7, Cursor: 100}}, encToken: enc, knownThreads: []string{"old"}} - reader := &fakeReader{threads: map[string][]string{"old": {"draft"}}, byID: map[string]Message{"draft": {ID: "draft", ThreadID: "old", Draft: true, ReceivedAt: time.Unix(200, 0)}}} - w := NewWorker(store, c, func(context.Context, string, []string) GmailReader { return reader }) - stats, err := w.RunOnce(context.Background()) - if err != nil { - t.Fatal(err) - } - if stats.Synced != 1 || len(store.upserted) != 0 || store.syncedCursor != 100 { - t.Fatalf("draft stored or moved incoming cursor: stats=%+v stored=%+v cursor=%d", stats, store.upserted, store.syncedCursor) - } -} - -func TestDeletedOldThreadDoesNotStallBackfill(t *testing.T) { - c := testCipher(t) - enc, _ := c.Encrypt("refresh") - store := &fakeStore{conns: []Connection{{UserID: 7, Cursor: 100}}, encToken: enc, knownThreads: []string{"deleted", "remaining"}} - reader := &fakeReader{threads: map[string][]string{"remaining": {"gone"}}, threadErrIDs: map[string]error{"deleted": &APIError{StatusCode: 404}}, getErrIDs: map[string]error{"gone": &APIError{StatusCode: 404}}} - w := NewWorker(store, c, func(context.Context, string, []string) GmailReader { return reader }) - stats, err := w.RunOnce(context.Background()) - if err != nil { - t.Fatal(err) - } - if stats.Synced != 1 || store.syncedSent == 0 { - t.Fatalf("permanently deleted mail stalled backfill: %+v sent_cursor=%d", stats, store.syncedSent) - } -} - -func TestIncomingSearchExcludesSentAndDrafts(t *testing.T) { - query := BuildQueryFor("me@example.test", 100, nil) - for _, term := range []string{"-in:sent", "-in:drafts"} { - if !strings.Contains(query, term) { - t.Fatalf("incoming discovery includes candidate content: %s", query) - } - } -} - -func TestOwnInboxDigestDoesNotEnterHiringMail(t *testing.T) { - c := testCipher(t) - enc, _ := c.Encrypt("refresh") - msg, err := parseMessage([]byte(`{"id":"digest","internalDate":"1700000000000","payload":{"headers":[{"name":"Subject","value":"Your daily hiring inbox"},{"name":"Auto-Submitted","value":"auto-generated"},{"name":"X-Freehire-Notification","value":"inbox-digest"}]}}`)) - if err != nil { - t.Fatal(err) - } - store := &fakeStore{conns: []Connection{{UserID: 7}}, encToken: enc} - reader := &fakeReader{ids: []string{"digest"}, byID: map[string]Message{"digest": msg}} - w := NewWorker(store, c, func(context.Context, string, []string) GmailReader { return reader }) - if _, err := w.RunOnce(context.Background()); err != nil { - t.Fatal(err) - } - if len(store.upserted) != 0 { - t.Fatal("generated digest entered the hiring inbox") - } -} diff --git a/internal/application/gmailsync/reader.go b/internal/application/gmailsync/reader.go index 358d6f74f1..e30e5897c8 100644 --- a/internal/application/gmailsync/reader.go +++ b/internal/application/gmailsync/reader.go @@ -5,29 +5,16 @@ import ( "time" ) -const ( - DirectionIncoming = "incoming" - DirectionOutgoing = "outgoing" -) - -// MessageRef identifies a message without reading its contents. -type MessageRef struct{ ID, ThreadID string } - -// Message is one fetched Gmail message with decoded bodies and provider direction. +// Message is one fetched Gmail message in domain form (bodies already decoded). type Message struct { - Draft bool - SystemNotification bool - Direction string - ToAddrs string - CcAddrs string - ID string - ThreadID string - FromAddr string - FromName string - Subject string - BodyText string - BodyHTML string - ReceivedAt time.Time + ID string + ThreadID string + FromAddr string + FromName string + Subject string + BodyText string + BodyHTML string + ReceivedAt time.Time // CalendarUID identifies the meeting an invitation attaches, and is "" for the mail // that carries none. It is what later proves a calendar entry is this same meeting — // the only link calmatch may make without asking the candidate. @@ -45,8 +32,6 @@ type GmailReader interface { // that knows it, and because a reader built for a search (see MailboxSearcher) has no // business carrying it. ListATSMessageIDs(ctx context.Context, selfAddr string, afterUnix int64) ([]string, error) - // ListSentMessages returns metadata only; callers fetch bodies only for known hiring threads. - ListSentMessages(ctx context.Context, afterUnix int64) ([]MessageRef, error) // ListThreadMessageIDs returns the ids of every message in a thread, so replies // that carry no ATS marker (personal recruiters, scheduling) are ingested // alongside the matched message that anchors the thread. diff --git a/internal/application/gmailsync/senders.go b/internal/application/gmailsync/senders.go index bf9643b344..2d85a4bd2f 100644 --- a/internal/application/gmailsync/senders.go +++ b/internal/application/gmailsync/senders.go @@ -142,7 +142,7 @@ func BuildQueryFor(selfAddr string, afterUnix int64, extraDomains []string) stri if afterUnix > 0 { q += fmt.Sprintf(" after:%d", afterUnix) } - return q + " -in:sent -in:drafts" + return q } // IsATSSender reports whether a From header (address or "Name ") comes from diff --git a/internal/application/gmailsync/sent_api_test.go b/internal/application/gmailsync/sent_api_test.go deleted file mode 100644 index 1e0f52cc01..0000000000 --- a/internal/application/gmailsync/sent_api_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package gmailsync - -import ( - "context" - "io" - "net/http" - "strings" - "testing" -) - -type sentPageTransport struct { - t *testing.T - calls int -} - -func (s *sentPageTransport) RoundTrip(req *http.Request) (*http.Response, error) { - s.calls++ - if req.URL.Query().Get("q") != "in:sent after:940" { - s.t.Errorf("query=%q", req.URL.Query().Get("q")) - } - body := `{"messages":[{"id":"one","threadId":"known"}],"nextPageToken":"next"}` - if s.calls == 2 { - if req.URL.Query().Get("pageToken") != "next" { - s.t.Error("missing next-page token") - } - body = `{"messages":[{"id":"two","threadId":"private"}]}` - } - return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil -} - -func TestSentDiscoveryPagesMetadataWithOverlap(t *testing.T) { - transport := &sentPageTransport{t: t} - reader := NewAPIReader(&http.Client{Transport: transport}, nil) - refs, err := reader.ListSentMessages(context.Background(), 1000) - if err != nil { - t.Fatal(err) - } - if transport.calls != 2 || len(refs) != 2 || refs[0].ThreadID != "known" || refs[1].ID != "two" { - t.Fatalf("calls=%d refs=%+v", transport.calls, refs) - } -} diff --git a/internal/application/gmailsync/worker.go b/internal/application/gmailsync/worker.go index 926d68c6a1..2e99a8a10a 100644 --- a/internal/application/gmailsync/worker.go +++ b/internal/application/gmailsync/worker.go @@ -2,21 +2,17 @@ package gmailsync import ( "context" - "errors" "log" - "net/http" "strings" - "time" "github.com/strelov1/freehire/internal/platform/tokencrypt" ) // Connection is a connected user the sync worker processes. type Connection struct { - UserID int64 - Email string - Cursor int64 // Unix watermark of the newest synced incoming message - SentCursor int64 // Run-start watermark of the last complete sent scan + UserID int64 + Email string + Cursor int64 // Unix watermark of the newest synced message } // StoredEmail is a fetched message ready to persist. @@ -30,8 +26,7 @@ type Store interface { ListConnected(ctx context.Context) ([]Connection, error) RefreshToken(ctx context.Context, userID int64) (encToken string, err error) UpsertEmail(ctx context.Context, e StoredEmail) error - SetSynced(ctx context.Context, userID, cursorUnix, sentCursor int64) error - ListThreadIDs(ctx context.Context, userID int64) ([]string, error) + SetSynced(ctx context.Context, userID, cursorUnix int64) error SetNeedsReconsent(ctx context.Context, userID int64) error } @@ -133,7 +128,6 @@ func (w *Worker) markRevoked(ctx context.Context, userID int64) outcome { func (w *Worker) SyncUser(ctx context.Context, u Connection) { _ = w.syncUser(ctx, u) } func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { - started := time.Now().Unix() encToken, err := w.store.RefreshToken(ctx, u.UserID) if err != nil { log.Printf("gmail-sync: user %d: read token: %v", u.UserID, err) @@ -177,7 +171,8 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { var threadIDs []string // fetch persists one message, deduping by id, tracking the watermark, and - // recording its thread for expansion. Both directions are retained; newest tracks incoming + // recording its thread for expansion. The user's own in-thread replies are + // skipped — the inbox stores inbound mail only. newest tracks the highest // ReceivedAt seen regardless of order; once any message in the wave fails, // it is reset to u.Cursor right before SetSynced (below) rather than merely // frozen at whatever it last reached — a newer message can easily succeed @@ -196,9 +191,6 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { seen[id] = true msg, err := reader.GetMessage(ctx, id) if err != nil { - if missingMessage(err) { - return - } if RevokedGrant(err) { log.Printf("gmail-sync: user %d: get %s: %v — marking needs_reconsent", u.UserID, id, err) revoked = true @@ -208,31 +200,19 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { sawFailure = true return } - if msg.SystemNotification { - if ts := msg.ReceivedAt.Unix(); ts > newest { - newest = ts - } - return - } - if msg.Draft { - return - } if msg.ThreadID != "" && !seenThread[msg.ThreadID] { seenThread[msg.ThreadID] = true threadIDs = append(threadIDs, msg.ThreadID) } - if msg.Direction == "" { - msg.Direction = DirectionIncoming - } - if u.Email != "" && strings.EqualFold(msg.FromAddr, u.Email) { - msg.Direction = DirectionOutgoing + if strings.EqualFold(msg.FromAddr, u.Email) { + return } if err := w.store.UpsertEmail(ctx, StoredEmail{UserID: u.UserID, Message: msg}); err != nil { log.Printf("gmail-sync: user %d: store %s: %v", u.UserID, id, err) sawFailure = true return } - if ts := msg.ReceivedAt.Unix(); msg.Direction == DirectionIncoming && ts > newest { + if ts := msg.ReceivedAt.Unix(); ts > newest { newest = ts } } @@ -243,40 +223,6 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { break } } - // Existing stored threads are the privacy boundary for outgoing discovery. - knownThreads, err := w.store.ListThreadIDs(ctx, u.UserID) - if err != nil { - log.Printf("gmail-sync: user %d: known threads: %v", u.UserID, err) - return outcomeFailed - } - known := make(map[string]bool, len(knownThreads)) - for _, tid := range knownThreads { - known[tid] = true - if u.SentCursor == 0 && !seenThread[tid] { - seenThread[tid] = true - threadIDs = append(threadIDs, tid) - } - } - if u.SentCursor != 0 && !revoked { - refs, err := reader.ListSentMessages(ctx, u.SentCursor) - if err != nil { - if RevokedGrant(err) { - return w.markRevoked(ctx, u.UserID) - } - log.Printf("gmail-sync: user %d: sent messages: %v", u.UserID, err) - sawFailure = true - } else { - for _, ref := range refs { - if known[ref.ThreadID] || seenThread[ref.ThreadID] { - fetch(ref.ID) - if revoked { - break - } - } - } - } - } - // Thread expansion: pull every sibling of a matched message's thread so a // reply with no ATS marker (a personal recruiter, a scheduling follow-up) is // ingested behind the anchor the search already found. Skipped once the grant @@ -287,16 +233,12 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { } siblings, err := reader.ListThreadMessageIDs(ctx, tid) if err != nil { - if missingMessage(err) { - continue - } if RevokedGrant(err) { log.Printf("gmail-sync: user %d: thread %s: %v — marking needs_reconsent", u.UserID, tid, err) revoked = true break } log.Printf("gmail-sync: user %d: thread %s: %v", u.UserID, tid, err) - sawFailure = true continue } for _, id := range siblings { @@ -313,9 +255,8 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { if sawFailure { newest = u.Cursor - started = u.SentCursor } - if err := w.store.SetSynced(ctx, u.UserID, newest, started); err != nil { + if err := w.store.SetSynced(ctx, u.UserID, newest); err != nil { log.Printf("gmail-sync: user %d: set synced: %v", u.UserID, err) return outcomeFailed } @@ -324,9 +265,3 @@ func (w *Worker) syncUser(ctx context.Context, u Connection) outcome { } return outcomeSynced } - -// A permanently removed provider resource has no content left to synchronize. -func missingMessage(err error) bool { - var apiErr *APIError - return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound -} diff --git a/internal/application/gmailsync/worker_test.go b/internal/application/gmailsync/worker_test.go index 4be685d0fd..4e6f4ea635 100644 --- a/internal/application/gmailsync/worker_test.go +++ b/internal/application/gmailsync/worker_test.go @@ -27,8 +27,6 @@ type fakeStore struct { encToken string upserted []StoredEmail upsertErrIDs map[string]bool // message ids on which UpsertEmail fails - syncedSent int64 - knownThreads []string syncedCursor int64 syncedCalled bool reconsentUsers []int64 @@ -44,10 +42,9 @@ func (f *fakeStore) UpsertEmail(_ context.Context, e StoredEmail) error { f.upserted = append(f.upserted, e) return nil } -func (f *fakeStore) SetSynced(_ context.Context, _, cursor, sentCursor int64) error { +func (f *fakeStore) SetSynced(_ context.Context, _, cursor int64) error { f.syncedCalled = true f.syncedCursor = cursor - f.syncedSent = sentCursor return nil } func (f *fakeStore) SetNeedsReconsent(_ context.Context, userID int64) error { @@ -58,13 +55,7 @@ func (f *fakeStore) SetNeedsReconsent(_ context.Context, userID int64) error { return nil } -func (f *fakeStore) ListThreadIDs(context.Context, int64) ([]string, error) { - return f.knownThreads, nil -} - type fakeReader struct { - sent []MessageRef - sentErr error ids []string byID map[string]Message threads map[string][]string // threadID -> message ids @@ -73,10 +64,6 @@ type fakeReader struct { threadErrIDs map[string]error // thread ids on which ListThreadMessageIDs fails } -func (f *fakeReader) ListSentMessages(context.Context, int64) ([]MessageRef, error) { - return f.sent, f.sentErr -} - func (f *fakeReader) ListATSMessageIDs(context.Context, string, int64) ([]string, error) { return f.ids, f.listErr } @@ -129,7 +116,7 @@ func TestRunOnceSyncsUser(t *testing.T) { // TestRunOnceExpandsThread locks in thread-expansion: a matched ATS message // pulls in every sibling of its thread, so a recruiter's reply from a personal // domain (which no allowlist/phrase would match) is ingested too. The user's own -// in-thread reply is retained as conversation history. +// in-thread reply is skipped — inbound mail only. func TestRunOnceExpandsThread(t *testing.T) { c := testCipher(t) enc, _ := c.Encrypt("refresh-token") @@ -158,11 +145,11 @@ func TestRunOnceExpandsThread(t *testing.T) { if !got["m1"] || !got["m3"] { t.Errorf("want anchor m1 and sibling m3 upserted, got %v", got) } - if !got["m9"] { - t.Error("user reply m9 must be retained") + if got["m9"] { + t.Error("user's own in-thread reply m9 should not be ingested") } - if len(store.upserted) != 3 { - t.Errorf("upserted = %d, want 3 (no dupes)", len(store.upserted)) + if len(store.upserted) != 2 { + t.Errorf("upserted = %d, want 2 (m1, m3; no dupes)", len(store.upserted)) } } @@ -475,7 +462,9 @@ func TestRunOnceRevokedTokenOnThreadListingMarksReconsent(t *testing.T) { } } -// A transient thread failure retains both cursors so its siblings can be retried. +// A thread listing that fails for any other reason still only skips that one thread's +// siblings — the anchor message it was expanding already stored fine, so the run is not +// failed over a single thread's own hiccup. Unchanged by the fix above. func TestRunOnceDoesNotDisconnectOverATransientThreadListingFailure(t *testing.T) { c := testCipher(t) enc, _ := c.Encrypt("refresh-token") @@ -501,8 +490,9 @@ func TestRunOnceDoesNotDisconnectOverATransientThreadListingFailure(t *testing.T if len(store.upserted) != 1 || store.upserted[0].Message.ID != "m1" { t.Fatalf("upserted = %v, want only the anchor m1 (thread expansion failed, not the anchor)", store.upserted) } - if stats.Failed != 1 || stats.Synced != 0 || stats.Reconsent != 0 { - t.Errorf("stats = %+v, want one failed connection with retry coverage", stats) + if stats.Failed != 0 || stats.Synced != 1 || stats.Reconsent != 0 { + t.Errorf("stats = %+v, want the connection cleanly synced — a thread's own transient "+ + "failure does not fail the whole run", stats) } } diff --git a/internal/application/inbox/inbox.go b/internal/application/inbox/inbox.go index 4ecbbf4daa..db230139d3 100644 --- a/internal/application/inbox/inbox.go +++ b/internal/application/inbox/inbox.go @@ -149,10 +149,6 @@ type Message struct { ID int64 Source string ExternalID string - Direction string - ThreadID string - ToAddrs string - CcAddrs string FromAddr string FromName string Subject string @@ -271,7 +267,7 @@ func (s *Service) Search(ctx context.Context, userID int64, q Query) (Page, erro out := make([]Message, 0, len(rows)) for _, r := range rows { m := Message{ - ID: r.ID, Source: r.Source, ExternalID: r.ExternalID, Direction: r.Direction, ThreadID: r.ThreadID, ToAddrs: r.ToAddrs, CcAddrs: r.CcAddrs, + ID: r.ID, Source: r.Source, ExternalID: r.ExternalID, FromAddr: r.FromAddr, FromName: r.FromName, Subject: r.Subject, Snippet: r.Snippet, ReceivedAt: r.ReceivedAt.Time, Read: r.Read, StatusSignal: pgStr(r.StatusSignal), @@ -302,7 +298,7 @@ func (s *Service) Get(ctx context.Context, userID, id int64) (Message, error) { return Message{}, err } return Message{ - ID: row.ID, Source: row.Source, ExternalID: row.ExternalID, Direction: row.Direction, ThreadID: row.ThreadID, ToAddrs: row.ToAddrs, CcAddrs: row.CcAddrs, + ID: row.ID, Source: row.Source, ExternalID: row.ExternalID, FromAddr: row.FromAddr, FromName: row.FromName, Subject: row.Subject, BodyText: row.BodyText, BodyHTML: row.BodyHtml, ReceivedAt: row.ReceivedAt.Time, Read: row.Read, diff --git a/internal/platform/db/gmail.sql.go b/internal/platform/db/gmail.sql.go index 47b7fc33bb..795c55669e 100644 --- a/internal/platform/db/gmail.sql.go +++ b/internal/platform/db/gmail.sql.go @@ -21,7 +21,7 @@ WHERE user_id = $1 AND ($3::text = '' OR source = $3) AND ($4::bool = false OR read_at IS NULL) AND ($5::text = '' OR status_signal = $5) - AND ($6::bool = false OR (classified_at IS NULL AND direction = 'incoming')) + AND ($6::bool = false OR classified_at IS NULL) AND ( $7::text = '' OR ($7 = 'linked' AND application_id IS NOT NULL) @@ -80,7 +80,7 @@ const countEmailsByState = `-- name: CountEmailsByState :many SELECT coalesce(status_signal, '')::text AS label, count(*)::bigint AS n, count(*) FILTER (WHERE read_at IS NULL)::bigint AS unread, - count(*) FILTER (WHERE classified_at IS NULL AND direction = 'incoming')::bigint AS unclassified, + count(*) FILTER (WHERE classified_at IS NULL)::bigint AS unclassified, count(*) FILTER (WHERE application_id IS NOT NULL)::bigint AS linked, count(*) FILTER (WHERE application_id IS NULL AND suggested_job_id IS NOT NULL)::bigint AS suggested FROM emails @@ -158,7 +158,7 @@ func (q *Queries) DeleteGmailConnection(ctx context.Context, userID int64) error } const getEmail = `-- name: GetEmail :one -SELECT emails.id, emails.source, emails.external_id, emails.thread_id, emails.direction, emails.to_addrs, emails.cc_addrs, emails.s3_key, emails.from_addr, emails.from_name, emails.subject, +SELECT emails.id, emails.source, emails.external_id, emails.s3_key, emails.from_addr, emails.from_name, emails.subject, emails.body_text, emails.body_html, emails.received_at, (emails.read_at IS NOT NULL)::boolean AS read, emails.job_id, emails.suggested_job_id, emails.status_signal, emails.link_source, -- The link is to the APPLICATION; the posting is how it is displayed while the @@ -183,10 +183,6 @@ type GetEmailRow struct { ID int64 `json:"id"` Source string `json:"source"` ExternalID string `json:"external_id"` - ThreadID string `json:"thread_id"` - Direction string `json:"direction"` - ToAddrs string `json:"to_addrs"` - CcAddrs string `json:"cc_addrs"` S3Key pgtype.Text `json:"s3_key"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` @@ -212,10 +208,6 @@ func (q *Queries) GetEmail(ctx context.Context, arg GetEmailParams) (GetEmailRow &i.ID, &i.Source, &i.ExternalID, - &i.ThreadID, - &i.Direction, - &i.ToAddrs, - &i.CcAddrs, &i.S3Key, &i.FromAddr, &i.FromName, @@ -237,7 +229,7 @@ func (q *Queries) GetEmail(ctx context.Context, arg GetEmailParams) (GetEmailRow } const getGmailConnection = `-- name: GetGmailConnection :one -SELECT user_id, email, status, sync_cursor, connected_at, last_synced_at, scopes, sent_sync_cursor, +SELECT user_id, email, status, sync_cursor, connected_at, last_synced_at, scopes, mentor_busy_sync_opted_in FROM gmail_connections WHERE user_id = $1 @@ -251,7 +243,6 @@ type GetGmailConnectionRow struct { ConnectedAt pgtype.Timestamptz `json:"connected_at"` LastSyncedAt pgtype.Timestamptz `json:"last_synced_at"` Scopes []string `json:"scopes"` - SentSyncCursor int64 `json:"sent_sync_cursor"` MentorBusySyncOptedIn bool `json:"mentor_busy_sync_opted_in"` } @@ -273,7 +264,6 @@ func (q *Queries) GetGmailConnection(ctx context.Context, userID int64) (GetGmai &i.ConnectedAt, &i.LastSyncedAt, &i.Scopes, - &i.SentSyncCursor, &i.MentorBusySyncOptedIn, ) return i, err @@ -327,7 +317,7 @@ SELECT id, from_addr, from_name, subject, body_text, body_html, received_at, FROM emails WHERE user_id = $1 AND job_id = $2::bigint - AND status_signal = 'interview_invitation' AND direction = 'incoming' + AND status_signal = 'interview_invitation' AND deleted_at IS NULL ORDER BY received_at DESC, id DESC LIMIT 1 @@ -389,16 +379,15 @@ func (q *Queries) GetInterviewInvitation(ctx context.Context, arg GetInterviewIn } const listConnectedGmailUsers = `-- name: ListConnectedGmailUsers :many -SELECT user_id, email, sync_cursor, sent_sync_cursor +SELECT user_id, email, sync_cursor FROM gmail_connections WHERE status = 'connected' AND email <> '' ` type ListConnectedGmailUsersRow struct { - UserID int64 `json:"user_id"` - Email string `json:"email"` - SyncCursor int64 `json:"sync_cursor"` - SentSyncCursor int64 `json:"sent_sync_cursor"` + UserID int64 `json:"user_id"` + Email string `json:"email"` + SyncCursor int64 `json:"sync_cursor"` } // Drives the sync worker: every connection still authorized AND holding a mailbox. @@ -422,12 +411,7 @@ func (q *Queries) ListConnectedGmailUsers(ctx context.Context) ([]ListConnectedG items := []ListConnectedGmailUsersRow{} for rows.Next() { var i ListConnectedGmailUsersRow - if err := rows.Scan( - &i.UserID, - &i.Email, - &i.SyncCursor, - &i.SentSyncCursor, - ); err != nil { + if err := rows.Scan(&i.UserID, &i.Email, &i.SyncCursor); err != nil { return nil, err } items = append(items, i) @@ -439,7 +423,7 @@ func (q *Queries) ListConnectedGmailUsers(ctx context.Context) ([]ListConnectedG } const listEmails = `-- name: ListEmails :many -SELECT emails.id, emails.source, emails.external_id, emails.thread_id, emails.direction, emails.to_addrs, emails.cc_addrs, emails.from_addr, emails.from_name, emails.subject, +SELECT emails.id, emails.source, emails.external_id, emails.from_addr, emails.from_name, emails.subject, left(regexp_replace(emails.body_text, E'\\s+', ' ', 'g'), 160)::text AS snippet, (CASE WHEN $2::bool THEN emails.body_text ELSE '' END)::text AS body_text, (CASE WHEN $2::bool THEN emails.body_html ELSE '' END)::text AS body_html, @@ -460,7 +444,7 @@ WHERE emails.user_id = $1 AND ($3::text = '' OR emails.source = $3) AND ($4::bool = false OR emails.read_at IS NULL) AND ($5::text = '' OR emails.status_signal = $5) - AND ($6::bool = false OR (emails.classified_at IS NULL AND emails.direction = 'incoming')) + AND ($6::bool = false OR emails.classified_at IS NULL) AND ( $7::text = '' OR ($7 = 'linked' AND emails.application_id IS NOT NULL) @@ -505,10 +489,6 @@ type ListEmailsRow struct { ID int64 `json:"id"` Source string `json:"source"` ExternalID string `json:"external_id"` - ThreadID string `json:"thread_id"` - Direction string `json:"direction"` - ToAddrs string `json:"to_addrs"` - CcAddrs string `json:"cc_addrs"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` Subject string `json:"subject"` @@ -574,10 +554,6 @@ func (q *Queries) ListEmails(ctx context.Context, arg ListEmailsParams) ([]ListE &i.ID, &i.Source, &i.ExternalID, - &i.ThreadID, - &i.Direction, - &i.ToAddrs, - &i.CcAddrs, &i.FromAddr, &i.FromName, &i.Subject, @@ -605,32 +581,6 @@ func (q *Queries) ListEmails(ctx context.Context, arg ListEmailsParams) ([]ListE return items, nil } -const listGmailThreadIDs = `-- name: ListGmailThreadIDs :many -SELECT DISTINCT thread_id FROM emails -WHERE user_id = $1 AND source = 'gmail' AND thread_id <> '' AND deleted_at IS NULL -` - -// Known hiring conversations are the boundary for sent-message body retrieval. -func (q *Queries) ListGmailThreadIDs(ctx context.Context, userID int64) ([]string, error) { - rows, err := q.db.Query(ctx, listGmailThreadIDs, userID) - if err != nil { - return nil, err - } - defer rows.Close() - items := []string{} - for rows.Next() { - var thread_id string - if err := rows.Scan(&thread_id); err != nil { - return nil, err - } - items = append(items, thread_id) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const listMentorBusySyncConnections = `-- name: ListMentorBusySyncConnections :many SELECT m.id AS mentor_id, gc.user_id FROM gmail_connections gc @@ -679,7 +629,7 @@ WHERE user_id = $1 AND deleted_at IS NULL AND ($2::text = '' OR source = $2) AND ($3::text = '' OR status_signal = $3) - AND ($4::bool = false OR (classified_at IS NULL AND direction = 'incoming')) + AND ($4::bool = false OR classified_at IS NULL) -- The listing's ` + "`" + `other` + "`" + ` default, and the same reading of it: asking FOR the label is -- asking for it (inbox.Query.ShowsOther), so ` + "`" + `?status=other` + "`" + ` marks the page it shows -- rather than nothing at all. @@ -803,18 +753,17 @@ func (q *Queries) SetGmailStatus(ctx context.Context, arg SetGmailStatusParams) const setGmailSynced = `-- name: SetGmailSynced :exec UPDATE gmail_connections -SET sync_cursor = $2, sent_sync_cursor = $3, last_synced_at = now() +SET sync_cursor = $2, last_synced_at = now() WHERE user_id = $1 ` type SetGmailSyncedParams struct { - UserID int64 `json:"user_id"` - SyncCursor int64 `json:"sync_cursor"` - SentSyncCursor int64 `json:"sent_sync_cursor"` + UserID int64 `json:"user_id"` + SyncCursor int64 `json:"sync_cursor"` } func (q *Queries) SetGmailSynced(ctx context.Context, arg SetGmailSyncedParams) error { - _, err := q.db.Exec(ctx, setGmailSynced, arg.UserID, arg.SyncCursor, arg.SentSyncCursor) + _, err := q.db.Exec(ctx, setGmailSynced, arg.UserID, arg.SyncCursor) return err } @@ -853,32 +802,11 @@ func (q *Queries) SoftDeleteEmail(ctx context.Context, arg SoftDeleteEmailParams } const upsertEmail = `-- name: UpsertEmail :exec -WITH stored AS ( INSERT INTO emails ( - user_id, source, external_id, thread_id, from_addr, from_name, - subject, body_text, body_html, received_at, ical_uid, direction, to_addrs, cc_addrs, read_at -) VALUES ($1, 'gmail', $2, $3, $4, $5, $6, $7, $8, $9, $10, - COALESCE(NULLIF($11::text, ''), 'incoming'), $12, $13, - CASE WHEN $11::text = 'outgoing' THEN now() ELSE NULL END) -ON CONFLICT (user_id, source, external_id) DO UPDATE -SET direction = EXCLUDED.direction, - to_addrs = EXCLUDED.to_addrs, - cc_addrs = EXCLUDED.cc_addrs, - read_at = CASE WHEN EXCLUDED.direction = 'outgoing' THEN COALESCE(emails.read_at, now()) ELSE emails.read_at END, - status_signal = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.status_signal END, - suggested_job_id = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.suggested_job_id END, - classified_at = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.classified_at END, - classification_model = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.classification_model END -RETURNING id, user_id, direction -), unqueued AS ( - DELETE FROM email_classification_outbox o USING stored s - WHERE o.email_id = s.id AND s.direction = 'outgoing' - RETURNING o.id -) -UPDATE application_events ae SET retracted_at = now() -FROM stored s -WHERE ae.user_id = s.user_id AND ae.source_ref = s.id - AND s.direction = 'outgoing' AND ae.kind = 'employer_reply' AND ae.retracted_at IS NULL + user_id, source, external_id, thread_id, from_addr, from_name, + subject, body_text, body_html, received_at, ical_uid +) VALUES ($1, 'gmail', $2, $3, $4, $5, $6, $7, $8, $9, $10) +ON CONFLICT (user_id, source, external_id) DO NOTHING ` type UpsertEmailParams struct { @@ -892,13 +820,10 @@ type UpsertEmailParams struct { BodyHtml string `json:"body_html"` ReceivedAt pgtype.Timestamptz `json:"received_at"` IcalUid string `json:"ical_uid"` - Direction string `json:"direction"` - ToAddrs string `json:"to_addrs"` - CcAddrs string `json:"cc_addrs"` } -// Gmail is idempotent; sent messages are already read and never enter employer triage. -// Refresh provider metadata without changing deletion, bodies or incoming reader state. +// Store a Gmail message, idempotent by (user_id, source, external_id) with +// source fixed to 'gmail'; the hosted path has its own insert (InsertHostedMessage). func (q *Queries) UpsertEmail(ctx context.Context, arg UpsertEmailParams) error { _, err := q.db.Exec(ctx, upsertEmail, arg.UserID, @@ -911,9 +836,6 @@ func (q *Queries) UpsertEmail(ctx context.Context, arg UpsertEmailParams) error arg.BodyHtml, arg.ReceivedAt, arg.IcalUid, - arg.Direction, - arg.ToAddrs, - arg.CcAddrs, ) return err } diff --git a/internal/platform/db/gmail_outgoing_integration_test.go b/internal/platform/db/gmail_outgoing_integration_test.go deleted file mode 100644 index 56641d3f07..0000000000 --- a/internal/platform/db/gmail_outgoing_integration_test.go +++ /dev/null @@ -1,267 +0,0 @@ -//go:build integration - -package db - -import ( - "context" - "testing" - "time" - - "github.com/jackc/pgx/v5/pgtype" -) - -func TestOutgoingMailNeverBecomesEmployerSignal(t *testing.T) { - pool := startPostgres(t) - q := New(pool) - ctx := context.Background() - user := insertUser(t, pool, "sent@example.test") - job := insertJob(t, pool, "sent-job") - applyToJob(t, pool, user, job, "applied") - p := UpsertEmailParams{UserID: user, ExternalID: "sent", ThreadID: "hiring", FromAddr: "alias@example.test", ToAddrs: "hr@example.test", Direction: "outgoing", Subject: "Re: Interview", ReceivedAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true}} - for range 2 { - if err := q.UpsertEmail(ctx, p); err != nil { - t.Fatal(err) - } - } - rows, err := q.ListEmails(ctx, ListEmailsParams{UserID: user, Lim: 10}) - if err != nil { - t.Fatal(err) - } - if len(rows) != 1 || rows[0].Direction != "outgoing" || rows[0].ToAddrs != "hr@example.test" || !rows[0].Read { - t.Fatalf("sent inbox row: %+v", rows) - } - id := rows[0].ID - pending, err := q.ListEmails(ctx, ListEmailsParams{UserID: user, Lim: 10, Unclassified: true}) - if err != nil { - t.Fatal(err) - } - if len(pending) != 0 { - t.Fatalf("sent mail entered triage listing: %+v", pending) - } - if _, err = q.EnqueuePendingEmailClassification(ctx); err != nil { - t.Fatal(err) - } - var n int - if err = pool.QueryRow(ctx, "SELECT count(*) FROM email_classification_outbox WHERE email_id=$1", id).Scan(&n); err != nil { - t.Fatal(err) - } - if n != 0 { - t.Fatal("sent mail enqueued") - } - // Even a stale queue row must never reach the classifier. - if _, err = pool.Exec(ctx, "INSERT INTO email_classification_outbox(email_id) VALUES ($1)", id); err != nil { - t.Fatal(err) - } - claimed, err := q.ClaimEmailClassificationBatch(ctx, ClaimEmailClassificationBatchParams{LeaseSeconds: 60, BatchSize: 100}) - if err != nil { - t.Fatal(err) - } - for _, row := range claimed { - if row.EmailID == id { - t.Fatal("sent mail leased for classification") - } - } - linkEmail(t, pool, id, job, "manual") - app, err := q.GetUserApplication(ctx, GetUserApplicationParams{UserID: user, JobID: job}) - if err != nil { - t.Fatal(err) - } - if app.LastActivityAt.Time.After(time.Now().Add(time.Minute)) { - t.Fatal("candidate reply reset employer silence") - } - - if err = q.RecordEmailApplicationEvent(ctx, RecordEmailApplicationEventParams{ID: id, UserID: user, EventSource: "gmail"}); err != nil { - t.Fatal(err) - } - if err = q.AdvanceUserJobStage(ctx, AdvanceUserJobStageParams{UserID: user, JobID: job, Stage: "interview", EmailID: id, EventSource: "gmail"}); err != nil { - t.Fatal(err) - } - stage, err := q.GetUserJobStage(ctx, GetUserJobStageParams{UserID: user, JobID: job}) - if err != nil { - t.Fatal(err) - } - if stage != "applied" { - t.Fatalf("sent mail changed stage to %s", stage) - } - if err = pool.QueryRow(ctx, "SELECT count(*) FROM application_events WHERE user_id=$1 AND kind IN ('employer_reply','stage_set')", user).Scan(&n); err != nil { - t.Fatal(err) - } - if n != 0 { - t.Fatal("sent mail created employer/stage events") - } - changed, err := q.AgentTriageEmail(ctx, AgentTriageEmailParams{ID: id, UserID: user, StatusSignal: pgtype.Text{String: "interview_invitation", Valid: true}}) - if err != nil { - t.Fatal(err) - } - if changed != 0 { - t.Fatal("candidate mail accepted employer classification") - } -} - -func TestReimportRepairsOutgoingAlias(t *testing.T) { - pool := startPostgres(t) - q := New(pool) - ctx := context.Background() - user := insertUser(t, pool, "old-alias@example.test") - job := insertJob(t, pool, "old-alias-job") - applyToJob(t, pool, user, job, "applied") - id := insertLinkedEmail(t, pool, user, "old-alias", job) - if _, err := pool.Exec(ctx, "UPDATE emails SET status_signal='interview_invitation', classified_at=now() WHERE id=$1", id); err != nil { - t.Fatal(err) - } - if err := q.RecordEmailApplicationEvent(ctx, RecordEmailApplicationEventParams{ID: id, UserID: user, EventSource: "gmail"}); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(ctx, "INSERT INTO email_classification_outbox(email_id) VALUES ($1)", id); err != nil { - t.Fatal(err) - } - if err := q.UpsertEmail(ctx, UpsertEmailParams{UserID: user, ExternalID: "old-alias", Direction: "outgoing", ToAddrs: "hr@example.test", ReceivedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}}); err != nil { - t.Fatal(err) - } - email, err := q.GetEmail(ctx, GetEmailParams{ID: id, UserID: user}) - if err != nil { - t.Fatal(err) - } - if email.Direction != "outgoing" || email.ToAddrs != "hr@example.test" || email.StatusSignal.Valid || !email.Read { - t.Fatalf("alias metadata not repaired: %+v", email) - } - var n int - if err = pool.QueryRow(ctx, "SELECT count(*) FROM application_events WHERE source_ref=$1 AND kind='employer_reply' AND retracted_at IS NULL", id).Scan(&n); err != nil { - t.Fatal(err) - } - if n != 0 { - t.Fatal("candidate reply retained employer event") - } - if err = pool.QueryRow(ctx, "SELECT count(*) FROM email_classification_outbox WHERE email_id=$1", id).Scan(&n); err != nil { - t.Fatal(err) - } - if n != 0 { - t.Fatal("candidate reply retained classification work") - } -} - -func TestOutgoingThreadMailAppearsAfterIncomingLink(t *testing.T) { - pool := startPostgres(t) - q, ctx := New(pool), context.Background() - user := insertUser(t, pool, "thread-view@example.test") - job := insertJob(t, pool, "thread-view-job") - otherJob := insertJob(t, pool, "thread-other-job") - applyToJob(t, pool, user, job, "applied") - for _, direction := range []string{"incoming", "outgoing"} { - if err := q.UpsertEmail(ctx, UpsertEmailParams{UserID: user, ExternalID: direction, ThreadID: "thread", Direction: direction, ReceivedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}}); err != nil { - t.Fatal(err) - } - } - incoming, err := q.GetEmailIDByExternalID(ctx, GetEmailIDByExternalIDParams{UserID: user, ExternalID: "incoming"}) - if err != nil { - t.Fatal(err) - } - outgoing, err := q.GetEmailIDByExternalID(ctx, GetEmailIDByExternalIDParams{UserID: user, ExternalID: "outgoing"}) - if err != nil { - t.Fatal(err) - } - assertSent := func(jobID int64, want bool) { - t.Helper() - rows, err := q.ListJobEmails(ctx, ListJobEmailsParams{UserID: user, JobID: pgtype.Int8{Int64: jobID, Valid: true}}) - if err != nil { - t.Fatal(err) - } - found := false - for _, row := range rows { - found = found || row.ID == outgoing - } - if found != want { - t.Fatalf("job %d sent message visible=%v, want %v", jobID, found, want) - } - } - assertSent(job, false) - // Classification may link the incoming message after both messages were synced. - linkEmail(t, pool, incoming, job, "manual") - assertSent(job, true) - state := readLinkState(t, pool, outgoing) - if state.jobID.Valid || state.applicationID.Valid { - t.Fatal("display inference persisted an outgoing attachment") - } - other := insertLinkedEmail(t, pool, user, "other-anchor", otherJob) - if _, err := pool.Exec(ctx, "UPDATE emails SET thread_id='thread' WHERE id=$1", other); err != nil { - t.Fatal(err) - } - assertSent(job, false) - assertSent(otherJob, false) - // A linked application whose posting is gone is still a conflicting context. - var orphan int64 - if err := pool.QueryRow(ctx, "INSERT INTO applications(user_id,company_slug,role_title) VALUES($1,'orphan','Role') RETURNING id", user).Scan(&orphan); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(ctx, "UPDATE emails SET job_id=NULL,application_id=$2 WHERE id=$1", other, orphan); err != nil { - t.Fatal(err) - } - assertSent(job, false) - // Explicit manual and agent attachments win over ambiguous conversation context. - for _, source := range []string{"manual", "agent"} { - linkEmail(t, pool, outgoing, otherJob, source) - assertSent(otherJob, true) - assertSent(job, false) - } - if _, err := pool.Exec(ctx, "UPDATE emails SET job_id=NULL,application_id=NULL,link_source=NULL WHERE id=$1", outgoing); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(ctx, "UPDATE emails SET deleted_at=now() WHERE id=$1", other); err != nil { - t.Fatal(err) - } - assertSent(job, true) - for _, mutation := range []string{"source='hosted'", "thread_id=''", "deleted_at=now()"} { - if _, err := pool.Exec(ctx, "UPDATE emails SET "+mutation+" WHERE id=$1", incoming); err != nil { - t.Fatal(err) - } - assertSent(job, false) - if _, err := pool.Exec(ctx, "UPDATE emails SET source='gmail',thread_id='thread',deleted_at=NULL WHERE id=$1", incoming); err != nil { - t.Fatal(err) - } - } - otherUser := insertUser(t, pool, "thread-other-user@example.test") - if _, err := pool.Exec(ctx, "UPDATE emails SET user_id=$2 WHERE id=$1", incoming, otherUser); err != nil { - t.Fatal(err) - } - assertSent(job, false) - if _, err := pool.Exec(ctx, "UPDATE emails SET user_id=$2 WHERE id=$1", incoming, user); err != nil { - t.Fatal(err) - } - for _, mutation := range []string{"source='hosted'", "thread_id=''"} { - if _, err := pool.Exec(ctx, "UPDATE emails SET "+mutation+" WHERE id IN ($1,$2)", incoming, outgoing); err != nil { - t.Fatal(err) - } - assertSent(job, false) - if _, err := pool.Exec(ctx, "UPDATE emails SET source='gmail',thread_id='thread' WHERE id IN ($1,$2)", incoming, outgoing); err != nil { - t.Fatal(err) - } - } -} - -func TestRecallExcludesSentAndRepairedAliases(t *testing.T) { - pool := startPostgres(t) - q, ctx := New(pool), context.Background() - user := insertUser(t, pool, "recall-sent@example.test") - job := insertJob(t, pool, "recall-sent-job") - now := time.Now() - if err := q.UpsertEmail(ctx, UpsertEmailParams{UserID: user, ExternalID: "alias", ReceivedAt: pgtype.Timestamptz{Time: now, Valid: true}}); err != nil { - t.Fatal(err) - } - args := ListEmailsForRecallParams{UserID: user, Since: pgtype.Timestamptz{Time: now.Add(-time.Hour), Valid: true}, Until: pgtype.Timestamptz{Time: now.Add(time.Hour), Valid: true}, Lim: 10} - rows, err := q.ListEmailsForRecall(ctx, args) - if err != nil || len(rows) != 1 { - t.Fatalf("incoming recall rows=%d err=%v", len(rows), err) - } - id := rows[0].ID - if err := q.UpsertEmail(ctx, UpsertEmailParams{UserID: user, ExternalID: "alias", Direction: "outgoing", ReceivedAt: pgtype.Timestamptz{Time: now, Valid: true}}); err != nil { - t.Fatal(err) - } - changed, err := q.SuggestJobForEmail(ctx, SuggestJobForEmailParams{ID: id, UserID: user, SuggestedJobID: job, Confidence: 1}) - if err != nil || changed != 0 { - t.Errorf("in-flight recall suggested repaired sent alias: changed=%d err=%v", changed, err) - } - rows, err = q.ListEmailsForRecall(ctx, args) - if err != nil || len(rows) != 0 { - t.Fatalf("sent alias entered recall: rows=%d err=%v", len(rows), err) - } -} diff --git a/internal/platform/db/mail_linking.sql.go b/internal/platform/db/mail_linking.sql.go index 079f56bba4..c1055397ac 100644 --- a/internal/platform/db/mail_linking.sql.go +++ b/internal/platform/db/mail_linking.sql.go @@ -148,7 +148,7 @@ const listEmailsForRecall = `-- name: ListEmailsForRecall :many SELECT id, from_addr, from_name, subject, body_text, body_html, received_at, ical_uid FROM emails WHERE user_id = $1 - AND deleted_at IS NULL AND direction = 'incoming' + AND deleted_at IS NULL AND job_id IS NULL AND application_id IS NULL AND received_at >= $2 @@ -241,24 +241,11 @@ func (q *Queries) ListEmailsForRecall(ctx context.Context, arg ListEmailsForReca } const listJobEmails = `-- name: ListJobEmails :many -SELECT e.id, e.source, e.direction, e.to_addrs, e.cc_addrs, e.from_addr, e.from_name, e.subject, e.status_signal, e.link_source, - e.received_at, (e.read_at IS NOT NULL)::boolean AS read -FROM emails e -WHERE e.user_id = $1 AND (e.job_id = $2 OR ( - -- Infer display membership after incoming mail is linked, even if its reply arrived first. - -- Explicit attachments win; conversations naming multiple jobs stay unassigned. - e.job_id IS NULL AND e.application_id IS NULL AND e.deleted_at IS NULL - AND e.direction = 'outgoing' AND e.source = 'gmail' AND e.thread_id <> '' - AND $2 = ( - SELECT min(incoming.job_id) FROM emails incoming - WHERE incoming.user_id = e.user_id AND incoming.source = e.source - AND incoming.thread_id = e.thread_id AND incoming.direction = 'incoming' - AND incoming.deleted_at IS NULL - HAVING count(DISTINCT incoming.job_id) = 1 - AND count(*) FILTER (WHERE incoming.job_id IS NULL AND incoming.application_id IS NOT NULL) = 0 - ) -)) -ORDER BY e.received_at DESC, e.id DESC +SELECT id, source, from_addr, from_name, subject, status_signal, link_source, + received_at, (read_at IS NOT NULL)::boolean AS read +FROM emails +WHERE user_id = $1 AND job_id = $2 +ORDER BY received_at DESC, id DESC ` type ListJobEmailsParams struct { @@ -269,9 +256,6 @@ type ListJobEmailsParams struct { type ListJobEmailsRow struct { ID int64 `json:"id"` Source string `json:"source"` - Direction string `json:"direction"` - ToAddrs string `json:"to_addrs"` - CcAddrs string `json:"cc_addrs"` FromAddr string `json:"from_addr"` FromName string `json:"from_name"` Subject string `json:"subject"` @@ -295,9 +279,6 @@ func (q *Queries) ListJobEmails(ctx context.Context, arg ListJobEmailsParams) ([ if err := rows.Scan( &i.ID, &i.Source, - &i.Direction, - &i.ToAddrs, - &i.CcAddrs, &i.FromAddr, &i.FromName, &i.Subject, @@ -341,7 +322,7 @@ UPDATE emails SET suggested_job_id = $1::bigint, match_confidence = $2::real WHERE id = $3 AND user_id = $4 - AND job_id IS NULL AND application_id IS NULL AND deleted_at IS NULL AND direction = 'incoming' + AND job_id IS NULL AND application_id IS NULL AND deleted_at IS NULL ` type SuggestJobForEmailParams struct { diff --git a/internal/platform/db/querier.go b/internal/platform/db/querier.go index 78330e9790..0e1ec0f247 100644 --- a/internal/platform/db/querier.go +++ b/internal/platform/db/querier.go @@ -4688,8 +4688,6 @@ type Querier interface { // silence ladder it reads from, so both channels clear the same bar from the same // source. ListGhostReportEvidence(ctx context.Context, jobIds []int64) ([]ListGhostReportEvidenceRow, error) - // Known hiring conversations are the boundary for sent-message body retrieval. - ListGmailThreadIDs(ctx context.Context, userID int64) ([]string, error) // The caller's hidden application ids, for the tracker's visibility switch. ListHiddenBuddyApplications(ctx context.Context, userID int64) ([]int64, error) // The companies carrying searchable jobs whose slug folds to one of the given keys, or IS one @@ -8491,8 +8489,8 @@ type Querier interface { // costs a second slot. Two concurrent first applications can both pass the count and land // one over the cap; the cap bounds abuse, it is not a quota anyone is billed against. UpsertDirectApplication(ctx context.Context, arg UpsertDirectApplicationParams) (int64, error) - // Gmail is idempotent; sent messages are already read and never enter employer triage. - // Refresh provider metadata without changing deletion, bodies or incoming reader state. + // Store a Gmail message, idempotent by (user_id, source, external_id) with + // source fixed to 'gmail'; the hosted path has its own insert (InsertHostedMessage). UpsertEmail(ctx context.Context, arg UpsertEmailParams) error // Issue (or replace) the outstanding code for one purpose. The composite primary key // makes this the whole "at most one live code per (user, purpose)" rule: a resend diff --git a/internal/platform/db/queries/gmail.sql b/internal/platform/db/queries/gmail.sql index 26c4e3ffb9..2f2541c2e6 100644 --- a/internal/platform/db/queries/gmail.sql +++ b/internal/platform/db/queries/gmail.sql @@ -6,7 +6,7 @@ -- reason again, one purpose further: `scopes` alone cannot say whether THIS consent was -- given, since it reuses the same calendar.readonly scope the candidate-side calendar -- grant already requests. -SELECT user_id, email, status, sync_cursor, connected_at, last_synced_at, scopes, sent_sync_cursor, +SELECT user_id, email, status, sync_cursor, connected_at, last_synced_at, scopes, mentor_busy_sync_opted_in FROM gmail_connections WHERE user_id = $1; @@ -48,7 +48,7 @@ SET email = EXCLUDED.email, -- Checked on the address rather than on `scopes` for two reasons: every row that predates -- the scopes column has an empty list and would be excluded by a scope test, and the -- scope string then has to be spelled in SQL as well as in Go. -SELECT user_id, email, sync_cursor, sent_sync_cursor +SELECT user_id, email, sync_cursor FROM gmail_connections WHERE status = 'connected' AND email <> ''; @@ -76,7 +76,7 @@ WHERE gc.status = 'connected' -- name: SetGmailSynced :exec UPDATE gmail_connections -SET sync_cursor = $2, sent_sync_cursor = $3, last_synced_at = now() +SET sync_cursor = $2, last_synced_at = now() WHERE user_id = $1; -- name: SetGmailStatus :exec @@ -102,40 +102,14 @@ DELETE FROM gmail_connections WHERE user_id = $1; -- release passes 'hosted') — the other source's mail is left untouched. DELETE FROM emails WHERE user_id = $1 AND source = $2; --- name: ListGmailThreadIDs :many --- Known hiring conversations are the boundary for sent-message body retrieval. -SELECT DISTINCT thread_id FROM emails -WHERE user_id = $1 AND source = 'gmail' AND thread_id <> '' AND deleted_at IS NULL; - -- name: UpsertEmail :exec --- Gmail is idempotent; sent messages are already read and never enter employer triage. -WITH stored AS ( +-- Store a Gmail message, idempotent by (user_id, source, external_id) with +-- source fixed to 'gmail'; the hosted path has its own insert (InsertHostedMessage). INSERT INTO emails ( - user_id, source, external_id, thread_id, from_addr, from_name, - subject, body_text, body_html, received_at, ical_uid, direction, to_addrs, cc_addrs, read_at -) VALUES ($1, 'gmail', $2, $3, $4, $5, $6, $7, $8, $9, sqlc.arg(ical_uid), - COALESCE(NULLIF(sqlc.arg(direction)::text, ''), 'incoming'), sqlc.arg(to_addrs), sqlc.arg(cc_addrs), - CASE WHEN sqlc.arg(direction)::text = 'outgoing' THEN now() ELSE NULL END) -ON CONFLICT (user_id, source, external_id) DO UPDATE --- Refresh provider metadata without changing deletion, bodies or incoming reader state. -SET direction = EXCLUDED.direction, - to_addrs = EXCLUDED.to_addrs, - cc_addrs = EXCLUDED.cc_addrs, - read_at = CASE WHEN EXCLUDED.direction = 'outgoing' THEN COALESCE(emails.read_at, now()) ELSE emails.read_at END, - status_signal = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.status_signal END, - suggested_job_id = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.suggested_job_id END, - classified_at = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.classified_at END, - classification_model = CASE WHEN EXCLUDED.direction = 'outgoing' THEN NULL ELSE emails.classification_model END -RETURNING id, user_id, direction -), unqueued AS ( - DELETE FROM email_classification_outbox o USING stored s - WHERE o.email_id = s.id AND s.direction = 'outgoing' - RETURNING o.id -) -UPDATE application_events ae SET retracted_at = now() -FROM stored s -WHERE ae.user_id = s.user_id AND ae.source_ref = s.id - AND s.direction = 'outgoing' AND ae.kind = 'employer_reply' AND ae.retracted_at IS NULL; + user_id, source, external_id, thread_id, from_addr, from_name, + subject, body_text, body_html, received_at, ical_uid +) VALUES ($1, 'gmail', $2, $3, $4, $5, $6, $7, $8, $9, sqlc.arg(ical_uid)) +ON CONFLICT (user_id, source, external_id) DO NOTHING; -- name: UpsertExternalEmail :one -- Store a message the caller's own harness fetched, under source 'external' and @@ -188,7 +162,7 @@ RETURNING id, (xmax = 0)::boolean AS inserted; -- without a GetEmail per message — which would also mark each one read. The -- snippet already detoasts body_text, so the extra column costs no extra read; -- it is guarded only to keep the web inbox's payload small. -SELECT emails.id, emails.source, emails.external_id, emails.thread_id, emails.direction, emails.to_addrs, emails.cc_addrs, emails.from_addr, emails.from_name, emails.subject, +SELECT emails.id, emails.source, emails.external_id, emails.from_addr, emails.from_name, emails.subject, left(regexp_replace(emails.body_text, E'\\s+', ' ', 'g'), 160)::text AS snippet, (CASE WHEN sqlc.arg(with_body)::bool THEN emails.body_text ELSE '' END)::text AS body_text, (CASE WHEN sqlc.arg(with_body)::bool THEN emails.body_html ELSE '' END)::text AS body_html, @@ -209,7 +183,7 @@ WHERE emails.user_id = $1 AND (sqlc.arg(src)::text = '' OR emails.source = sqlc.arg(src)) AND (sqlc.arg(unread)::bool = false OR emails.read_at IS NULL) AND (sqlc.arg(status)::text = '' OR emails.status_signal = sqlc.arg(status)) - AND (sqlc.arg(unclassified)::bool = false OR (emails.classified_at IS NULL AND emails.direction = 'incoming')) + AND (sqlc.arg(unclassified)::bool = false OR emails.classified_at IS NULL) AND ( sqlc.arg(link)::text = '' OR (sqlc.arg(link) = 'linked' AND emails.application_id IS NOT NULL) @@ -252,7 +226,7 @@ WHERE user_id = $1 AND (sqlc.arg(src)::text = '' OR source = sqlc.arg(src)) AND (sqlc.arg(unread)::bool = false OR read_at IS NULL) AND (sqlc.arg(status)::text = '' OR status_signal = sqlc.arg(status)) - AND (sqlc.arg(unclassified)::bool = false OR (classified_at IS NULL AND direction = 'incoming')) + AND (sqlc.arg(unclassified)::bool = false OR classified_at IS NULL) AND ( sqlc.arg(link)::text = '' OR (sqlc.arg(link) = 'linked' AND application_id IS NOT NULL) @@ -296,13 +270,13 @@ SELECT id, from_addr, from_name, subject, body_text, body_html, received_at, FROM emails WHERE user_id = $1 AND job_id = sqlc.arg(job_id)::bigint - AND status_signal = 'interview_invitation' AND direction = 'incoming' + AND status_signal = 'interview_invitation' AND deleted_at IS NULL ORDER BY received_at DESC, id DESC LIMIT 1; -- name: GetEmail :one -SELECT emails.id, emails.source, emails.external_id, emails.thread_id, emails.direction, emails.to_addrs, emails.cc_addrs, emails.s3_key, emails.from_addr, emails.from_name, emails.subject, +SELECT emails.id, emails.source, emails.external_id, emails.s3_key, emails.from_addr, emails.from_name, emails.subject, emails.body_text, emails.body_html, emails.received_at, (emails.read_at IS NOT NULL)::boolean AS read, emails.job_id, emails.suggested_job_id, emails.status_signal, emails.link_source, -- The link is to the APPLICATION; the posting is how it is displayed while the @@ -343,7 +317,7 @@ WHERE user_id = $1 AND deleted_at IS NULL AND (sqlc.arg(src)::text = '' OR source = sqlc.arg(src)) AND (sqlc.arg(status)::text = '' OR status_signal = sqlc.arg(status)) - AND (sqlc.arg(unclassified)::bool = false OR (classified_at IS NULL AND direction = 'incoming')) + AND (sqlc.arg(unclassified)::bool = false OR classified_at IS NULL) -- The listing's `other` default, and the same reading of it: asking FOR the label is -- asking for it (inbox.Query.ShowsOther), so `?status=other` marks the page it shows -- rather than nothing at all. @@ -387,7 +361,7 @@ WHERE id = $1 AND user_id = $2; SELECT coalesce(status_signal, '')::text AS label, count(*)::bigint AS n, count(*) FILTER (WHERE read_at IS NULL)::bigint AS unread, - count(*) FILTER (WHERE classified_at IS NULL AND direction = 'incoming')::bigint AS unclassified, + count(*) FILTER (WHERE classified_at IS NULL)::bigint AS unclassified, count(*) FILTER (WHERE application_id IS NOT NULL)::bigint AS linked, count(*) FILTER (WHERE application_id IS NULL AND suggested_job_id IS NOT NULL)::bigint AS suggested FROM emails diff --git a/internal/platform/db/queries/mail_linking.sql b/internal/platform/db/queries/mail_linking.sql index e13d92f3b4..486ab0aced 100644 --- a/internal/platform/db/queries/mail_linking.sql +++ b/internal/platform/db/queries/mail_linking.sql @@ -29,24 +29,11 @@ WHERE uj.user_id = $1 AND uj.job_id = $2; -- name: ListJobEmails :many -- The emails linked to one of the caller's applications, newest first, for the -- application detail page. -SELECT e.id, e.source, e.direction, e.to_addrs, e.cc_addrs, e.from_addr, e.from_name, e.subject, e.status_signal, e.link_source, - e.received_at, (e.read_at IS NOT NULL)::boolean AS read -FROM emails e -WHERE e.user_id = $1 AND (e.job_id = $2 OR ( - -- Infer display membership after incoming mail is linked, even if its reply arrived first. - -- Explicit attachments win; conversations naming multiple jobs stay unassigned. - e.job_id IS NULL AND e.application_id IS NULL AND e.deleted_at IS NULL - AND e.direction = 'outgoing' AND e.source = 'gmail' AND e.thread_id <> '' - AND $2 = ( - SELECT min(incoming.job_id) FROM emails incoming - WHERE incoming.user_id = e.user_id AND incoming.source = e.source - AND incoming.thread_id = e.thread_id AND incoming.direction = 'incoming' - AND incoming.deleted_at IS NULL - HAVING count(DISTINCT incoming.job_id) = 1 - AND count(*) FILTER (WHERE incoming.job_id IS NULL AND incoming.application_id IS NOT NULL) = 0 - ) -)) -ORDER BY e.received_at DESC, e.id DESC; +SELECT id, source, from_addr, from_name, subject, status_signal, link_source, + received_at, (read_at IS NOT NULL)::boolean AS read +FROM emails +WHERE user_id = $1 AND job_id = $2 +ORDER BY received_at DESC, id DESC; -- name: ConfirmEmailLink :execrows -- Promote a suggested link to a confirmed one: the suggestion becomes job_id with @@ -119,7 +106,7 @@ WHERE id = $1 AND user_id = $2; SELECT id, from_addr, from_name, subject, body_text, body_html, received_at, ical_uid FROM emails WHERE user_id = $1 - AND deleted_at IS NULL AND direction = 'incoming' + AND deleted_at IS NULL AND job_id IS NULL AND application_id IS NULL AND received_at >= sqlc.arg(since) @@ -153,7 +140,7 @@ UPDATE emails SET suggested_job_id = sqlc.arg(suggested_job_id)::bigint, match_confidence = sqlc.arg(confidence)::real WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id) - AND job_id IS NULL AND application_id IS NULL AND deleted_at IS NULL AND direction = 'incoming'; + AND job_id IS NULL AND application_id IS NULL AND deleted_at IS NULL; -- name: GetEmailIDByExternalID :one -- One message's id from the identifier its provider gave it, scoped to the caller. diff --git a/openapi/api.openapi.json b/openapi/api.openapi.json index c51031c258..1a4be2cd42 100644 --- a/openapi/api.openapi.json +++ b/openapi/api.openapi.json @@ -26221,15 +26221,6 @@ "source": { "type": "string" }, - "direction": { - "type": "string" - }, - "to_addrs": { - "type": "string" - }, - "cc_addrs": { - "type": "string" - }, "from_addr": { "type": "string" }, @@ -26280,18 +26271,6 @@ "external_id": { "type": "string" }, - "direction": { - "type": "string" - }, - "to_addrs": { - "type": "string" - }, - "cc_addrs": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, "from_addr": { "type": "string" }, @@ -26429,18 +26408,6 @@ "external_id": { "type": "string" }, - "direction": { - "type": "string" - }, - "to_addrs": { - "type": "string" - }, - "cc_addrs": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, "from_addr": { "type": "string" }, diff --git a/openspec/changes/gmail-outgoing/.openspec.yaml b/openspec/changes/gmail-outgoing/.openspec.yaml deleted file mode 100644 index be831cee61..0000000000 --- a/openspec/changes/gmail-outgoing/.openspec.yaml +++ /dev/null @@ -1,2 +0,0 @@ -schema: spec-driven -created: 2026-11-14 diff --git a/openspec/changes/gmail-outgoing/design.md b/openspec/changes/gmail-outgoing/design.md deleted file mode 100644 index 22e9094778..0000000000 --- a/openspec/changes/gmail-outgoing/design.md +++ /dev/null @@ -1,27 +0,0 @@ -## Context - -Gmail synchronization finds incoming hiring-shaped messages, expands their threads, then discards self-authored siblings. Its timestamp cursor cannot discover later outgoing replies without an incoming anchor. - -## Goals / Non-Goals - -Capture outgoing Gmail messages in known hiring threads, including older threads and aliases, and expose direction and recipients. Do not import unrelated sent message bodies, send email, add model calls, implement the digest, or change hosted email transport. - -## Decisions - -Use Gmail's SENT label as the authoritative direction, retaining a primary-address fallback for existing readers. Persist direction (incoming/outgoing) and To/Cc headers. Existing messages default to incoming. Outgoing mail is stored read and excluded from classification queues, employer events, stage writes and invitation selection. - -Add a separate sent synchronization cursor to gmail_connections. At its initial zero value expand known stored Gmail threads once to backfill their sent replies. On later runs page through sent message identifiers and thread identifiers since the previous successful run, fetching bodies only for known hiring threads. Use run-start time with a short overlap so an in-flight send or same-second timestamp is retried safely. Preserve both cursors after transient failures; revoked-grant handling stays shared. Upserts remain idempotent and refresh provider direction/recipient metadata on conflict. A previously misidentified alias reply loses its employer classification, pending work and live employer-reply event when recognized as outgoing. Historical stage choices are not reversed automatically. Permanently missing messages/threads are skipped; drafts are never stored. Incoming watermark advances only on incoming messages. - -Expose direction and recipients in inbox list/detail and display Sent with recipients in the web inbox. Preserve incoming defaults for all other sources. Outgoing messages do not receive employer-status actions. - -Application mail views derive an unattached outgoing reply's membership from its Gmail conversation at read time, so an incoming message linked after synchronization also reveals earlier replies. Infer only within the same user, source and nonempty thread, with one unambiguous linked incoming job. Conflicting jobs and application-only incoming links prevent inference; explicit manual and agent attachments take precedence. This projection persists no link or employer activity. Recall selection and suggestion writes accept incoming mail only, including when alias repair occurs during recall. Follow-up drafts choose the newest incoming sender rather than the candidate's own later reply. - -## Risks / Trade-offs - -- First backfill traverses existing threads once; later passes read sent metadata and fetch only relevant content. -- A missing SENT label is handled for the primary connected address; Gmail labels identify aliases. -- Read-only synchronization cannot prove what a candidate communicated outside this mailbox or in another thread. - -## Migration Plan - -Apply the additive migration before deploying binaries. Old binaries ignore the new columns; rollback binaries safely without dropping data. No production deployment is part of this change. diff --git a/openspec/changes/gmail-outgoing/proposal.md b/openspec/changes/gmail-outgoing/proposal.md deleted file mode 100644 index 8ed2583bc9..0000000000 --- a/openspec/changes/gmail-outgoing/proposal.md +++ /dev/null @@ -1,23 +0,0 @@ -## Why - -The inbox discards the candidate's replies, so a future digest cannot describe both sides of a hiring conversation. Sync must capture outgoing replies without treating them as employer decisions. - -## What Changes - -- Store Gmail direction and recipients and expose them to inbox readers. -- Backfill sent replies in existing hiring threads once and discover new sent replies even when no new inbound anchor arrives. -- Exclude outgoing messages from classification, employer-reply events and automatic stage changes. - -## Capabilities - -### New Capabilities - -- `gmail-outgoing`: Read-only synchronization of sent messages in known hiring conversations. - -### Modified Capabilities - -None. - -## Impact - -Gmail sync, SQL schema and queries, inbox API and web rendering, tests and mail documentation. No additional OAuth scope, sending capability, hosted-mail transport or model calls. diff --git a/openspec/changes/gmail-outgoing/specs/gmail-outgoing/spec.md b/openspec/changes/gmail-outgoing/specs/gmail-outgoing/spec.md deleted file mode 100644 index 8c8e387ef7..0000000000 --- a/openspec/changes/gmail-outgoing/specs/gmail-outgoing/spec.md +++ /dev/null @@ -1,52 +0,0 @@ -## ADDED Requirements - -### Requirement: Capture outgoing hiring messages -The system SHALL store sent Gmail messages only in known hiring threads, with direction and recipient headers, using existing read-only authorization. - -#### Scenario: Reply from an alias -- **WHEN** a known hiring thread contains a message labelled SENT from a different address -- **THEN** it is stored as outgoing with its To and Cc headers - -#### Scenario: Unrelated outgoing message -- **WHEN** a sent message belongs to an unknown thread -- **THEN** its body is not fetched or stored - -### Requirement: Discover outgoing updates independently -The system SHALL backfill known threads once and discover new sent replies without a new incoming anchor. Failed passes MUST preserve retry coverage and repeated passes MUST NOT duplicate messages. - -#### Scenario: Reply to an old thread -- **WHEN** a candidate sends a reply in a stored thread after its incoming synchronization watermark -- **THEN** the next successful pass stores the reply even with no new incoming mail - -#### Scenario: Transient thread failure -- **WHEN** a thread or message cannot be fetched -- **THEN** the pass reports failure and retains its previous cursors for retry - -### Requirement: Separate candidate mail from employer decisions -Outgoing messages MUST NOT be classified as employer signals, count as employer replies, advance stages, or increase unread counts. Inbox readers SHALL expose their direction and recipients. - -#### Scenario: Candidate confirms interview -- **WHEN** the candidate sends an interview confirmation -- **THEN** it is displayed as sent and does not enqueue classification or create an employer event - -### Requirement: Preserve application conversation context -Application mail views SHALL include unattached outgoing Gmail replies when the same user's live incoming messages in the same source and nonempty thread identify one unambiguous job. Explicit attachments MUST take precedence. Display inference MUST NOT persist a link or employer activity. - -#### Scenario: Incoming link arrives after reply synchronization -- **WHEN** an incoming hiring message is linked after its outgoing reply was stored -- **THEN** the application mail view includes the reply without another synchronization pass - -#### Scenario: Ambiguous conversation -- **WHEN** incoming messages in a conversation name different jobs or include an application-only link -- **THEN** the view does not infer an unattached reply's job, while preserving explicit manual or agent attachments - -### Requirement: Keep recall and follow-up employer-only -Recall candidate selection and suggestion writes MUST accept incoming messages only. Follow-up drafts MUST use the newest incoming sender, even when a later outgoing reply is visible. - -#### Scenario: Alias repaired during recall -- **WHEN** recall selected a message before synchronization identifies it as outgoing -- **THEN** the pending recall cannot write an employer-message suggestion for that row - -#### Scenario: Candidate sends the newest reply -- **WHEN** an application has a newer candidate reply after the recruiter's last message -- **THEN** the follow-up draft retains the recruiter's address as its recipient diff --git a/openspec/changes/gmail-outgoing/tasks.md b/openspec/changes/gmail-outgoing/tasks.md deleted file mode 100644 index 4954c18fe9..0000000000 --- a/openspec/changes/gmail-outgoing/tasks.md +++ /dev/null @@ -1,16 +0,0 @@ -## 1. Synchronization - -- [x] 1.1 Test and implement SENT parsing, known-thread backfill and independent incremental discovery with retry-safe cursors. - -## 2. Persistence and readers - -- [x] 2.1 Test and implement additive schema, outgoing classification/event guards, inbox API fields and sent-message rendering. - -## 3. Verification - -- [x] 3.1 Update mail documentation, run focused and repository checks, simplify and review the complete change. - -## Validation - -This delivery is split across the mail-direction safety and Gmail sent-mail stages. -Stage-specific checks are recorded with each pull request; final verification is pending. diff --git a/typespec/mail.tsp b/typespec/mail.tsp index 5f1bd07803..4db729c69b 100644 --- a/typespec/mail.tsp +++ b/typespec/mail.tsp @@ -46,10 +46,6 @@ model InboxMessage { id: int64; source: string; external_id: string; - direction?: string; - to_addrs?: string; - cc_addrs?: string; - thread_id?: string; from_addr: string; from_name: string; subject: string; @@ -65,10 +61,6 @@ model InboxEmail { id: int64; source: string; external_id: string; - direction?: string; - to_addrs?: string; - cc_addrs?: string; - thread_id?: string; from_addr: string; from_name: string; subject: string; @@ -119,9 +111,6 @@ model InboxIngested { model InboxApplicationEmail { id: int64; source: string; - direction?: string; - to_addrs?: string; - cc_addrs?: string; from_addr: string; from_name: string; subject: string; diff --git a/web/src/lib/components/InboxView.messages.ts b/web/src/lib/components/InboxView.messages.ts index 5b6bdf2e9e..2a64ed3c34 100644 --- a/web/src/lib/components/InboxView.messages.ts +++ b/web/src/lib/components/InboxView.messages.ts @@ -6,9 +6,6 @@ import { defineMessages, plurals } from '#lib/i18n/t.js'; export const messages = defineMessages( { loading: 'Loading…', - sent: 'Sent', - to: 'To', - cc: 'Cc', tabs: { inbox: 'Inbox', settings: 'Settings', @@ -81,9 +78,6 @@ export const messages = defineMessages( { ru: { loading: 'Загрузка…', - sent: 'Отправлено', - to: 'Кому', - cc: 'Копия', tabs: { inbox: 'Входящие', settings: 'Настройки', diff --git a/web/src/lib/components/InboxView.svelte b/web/src/lib/components/InboxView.svelte index 5c94f44997..8acdaca5da 100644 --- a/web/src/lib/components/InboxView.svelte +++ b/web/src/lib/components/InboxView.svelte @@ -631,9 +631,7 @@ ? 'font-medium text-foreground/90' : 'font-semibold text-foreground'}" > - {m.direction === 'outgoing' - ? `${s.sent} · ${m.to_addrs || m.from_addr}` - : m.from_name || m.from_addr} + {m.from_name || m.from_addr} {timeAgo(m.received_at, locale())}· {msg.from_addr} {/if} - {#if msg.direction === 'outgoing'}{s.sent}{/if} {timeAgo(msg.received_at, locale())} @@ -720,15 +717,9 @@ - {#if msg.to_addrs}
- {s.to}: {msg.to_addrs} -
{/if} - {#if msg.cc_addrs}
- {s.cc}: {msg.cc_addrs} -
{/if} {@const linkState = inboxLinkState(msg, lastUnlinked)}