From 83881c775c217bbeeff6a3c92bfc8cce141453a5 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 17 Nov 2026 12:50:58 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Customers:=20audit=20activity=20(st?= =?UTF-8?q?ep=20D)=20and=20"Same=20person=3F"=20hints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 6 of RFC #18742. - The sweep reads the dashboard audit log: one acted edge per person per day and a logged_in edge on sign-in days. Only user, day and kind of action are read. An audit edge goes when its day leaves the audit retention. - Hints between a customer and a suggested person when an address starts like a login. Names are never compared. Yes makes the identity theirs, no pins the pair. POST /api/customers/hints/{hid}/answer, audited. - security-model.md: the customers store, people who never signed up, and the github: access-list assumption. Step E (budgeted GitHub search on accept) is not built: the GitHub client has no comment or mention search. Refs #18742 Signed-off-by: Andy Anderson --- .../added-18742-customers-hints-audit.md | 1 + dashboard/openapi.json | 66 +++++++ src/cmd/hive/customers_sweep.go | 69 +++++++ src/cmd/hive/customers_sweep_test.go | 59 ++++++ src/cmd/hive/customerswire.go | 4 + src/docs/api-reference.md | 4 +- src/docs/api-reference/customers.md | 15 +- src/docs/dashboard-sections.md | 2 +- src/docs/design/customers.md | 21 ++ src/docs/security-model.md | 23 +++ src/pkg/customers/hints.go | 183 ++++++++++++++++++ src/pkg/customers/hints_test.go | 180 +++++++++++++++++ src/pkg/customers/ingest.go | 4 + src/pkg/customers/resolve.go | 1 + src/pkg/customers/service.go | 57 +++++- src/pkg/dashboard/api_customers.go | 32 +++ src/pkg/dashboard/api_customers_test.go | 15 +- src/pkg/dashboard/customers_ui_test.go | 7 +- src/pkg/dashboard/static-src/js/customers.js | 26 ++- src/pkg/dashboard/static/index.html | 26 ++- 20 files changed, 776 insertions(+), 19 deletions(-) create mode 100644 changelog.d/added-18742-customers-hints-audit.md create mode 100644 src/pkg/customers/hints.go create mode 100644 src/pkg/customers/hints_test.go diff --git a/changelog.d/added-18742-customers-hints-audit.md b/changelog.d/added-18742-customers-hints-audit.md new file mode 100644 index 0000000000..f2b22089d6 --- /dev/null +++ b/changelog.d/added-18742-customers-hints-audit.md @@ -0,0 +1 @@ +- **Customers: audit activity and "Same person?" hints (#18742).** The discovery sweep now reads the dashboard audit log: a customer gets one `acted` edge per day they did something and a `logged_in` edge on days they signed in. Only the user, the day and the kind of action are read, never an audit line's detail, and an edge goes when its day leaves the 90-day audit retention. Hive also raises "Same person?" questions when a suggested address starts like a customer's login (or a suggested login like one of their addresses); names are never compared, short and role addresses are skipped, and nothing is linked until the owner or a read-write user answers on the profile: yes makes the suggested identity theirs, no pins the pair so it is not asked again (`POST /api/customers/hints/{hid}/answer`, audited as `customer_hint_answer`). `src/docs/security-model.md` now describes the customers store, the position on people who never signed up, and the one trust assumption in identity linking: a `github:` access-list entry is taken as proof of that GitHub login. The budgeted GitHub search on accept is not part of this change. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 8e70a094c0..fd0d0ace68 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -2063,6 +2063,72 @@ } } }, + "/api/customers/hints/{hid}/answer": { + "post": { + "tags": [ + "Customers" + ], + "summary": "Answer a \"Same person?\" question", + "description": "Hive raises a question when a suggested person's address starts like a customer's login, or the reverse. Nothing is linked until it is answered. same true makes the suggested identity the customer's own and deletes the suggestion; same false closes the question and remembers it so it is not asked again. A question between two customers is answered by merging them, so same true on one is refused with 400. Owner or read-write. Audited as customer_hint_answer.", + "parameters": [ + { + "name": "hid", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Hint id" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "same" + ], + "properties": { + "same": { + "type": "boolean" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The customer after the answer", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Customer profile as the viewer sees it, as returned by GET /api/customers/{id}" + } + } + } + }, + "400": { + "description": "Malformed body, or a customer-to-customer question answered yes" + }, + "403": { + "description": "Owner or read-write access required" + }, + "404": { + "description": "No such question, customer or suggestion" + }, + "409": { + "description": "The identity already belongs to another customer" + }, + "503": { + "description": "Customers are turned off on this hive" + } + } + } + }, "/api/customers/suggestions/{sid}/accept": { "post": { "tags": [ diff --git a/src/cmd/hive/customers_sweep.go b/src/cmd/hive/customers_sweep.go index 055eccdff8..b4618818ac 100644 --- a/src/cmd/hive/customers_sweep.go +++ b/src/cmd/hive/customers_sweep.go @@ -7,6 +7,7 @@ import ( "time" "github.com/hivecommons/hive/pkg/claims" + "github.com/hivecommons/hive/pkg/compliance" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/customers" "github.com/hivecommons/hive/pkg/dashboard" @@ -44,6 +45,16 @@ const ( customersSourceMail = "inbox_mail" customersSourceCalendar = "calendar" customersSourceMeetings = "meetings" + customersSourceAudit = "audit_log" +) + +const ( + // customersAuditWindow is how many recent audit entries one pass reads. + customersAuditWindow = 5000 + // customersLoginActionMarker marks an audit action that is a sign-in. + customersLoginActionMarker = "login" + // customersAuditDayLayout is the day an audit reference names. + customersAuditDayLayout = "2006-01-02" ) // customersSources is one sweep's reading of the hive's local state. @@ -60,12 +71,19 @@ type customersSources struct { mail []inbox.Item events []schedule.Event meetings []meetings.Meeting + // audit is the recent dashboard audit log (step D). + audit []dashboard.AuditEntry } // customersSources reads the local stores. A store that is off or fails to // list contributes nothing this pass. func (b *boot) customersSources(ctx context.Context, cfg *config.Config) customersSources { src := customersSources{cfg: cfg, last: b.lastActionable.Load()} + if b.dashSrv != nil { + if log := b.dashSrv.GetAudit(); log != nil { + src.audit = log.Recent(customersAuditWindow) + } + } if b.ownerIdentity != nil { src.ownerLogin = b.ownerIdentity.Status().Login } @@ -127,6 +145,7 @@ func customersSweepInput(src customersSources) customers.SweepInput { in.Users, in.Links = customersUsers(src) in.Sightings = append(in.Sightings, customersGitHubSightings(src)...) in.Sightings = append(in.Sightings, customersLocalSightings(src)...) + in.Sightings = append(in.Sightings, customersAuditSightings(src)...) return in } @@ -369,6 +388,7 @@ func (b *boot) customersResolvers() customers.Resolvers { customers.RefMeeting: customersMeetingResolver{b: b}, customers.RefEvent: customersEventResolver{b: b}, customers.RefInbox: customersInboxResolver{b: b}, + customers.RefAudit: customersAuditResolver{now: time.Now}, } } @@ -446,3 +466,52 @@ func (r customersInboxResolver) Exists(ref string) bool { } func (r customersInboxResolver) Visible(_ string, v customers.Viewer) bool { return v.Full } + +// customersAuditSightings is step D: what a dashboard user did, as one edge +// per person per day. The audit log carries the user and the day; the +// action's detail is never read, so nothing a person typed is copied. +// Pseudo-users such as the system and an unproxied local session match no +// customer and are dropped by the store. +func customersAuditSightings(src customersSources) []customers.Sighting { + type key struct{ user, pred, day string } + seen := map[key]bool{} + var out []customers.Sighting + for _, e := range src.audit { + user := strings.TrimSpace(e.User) + if user == "" { + continue + } + at, err := time.Parse(time.RFC3339, e.Timestamp) + if err != nil { + continue + } + day := at.UTC().Format(customersAuditDayLayout) + pred := customers.PredActed + if strings.Contains(strings.ToLower(e.Action), customersLoginActionMarker) { + pred = customers.PredLoggedIn + } + k := key{strings.ToLower(user), pred, day} + if seen[k] { + continue + } + seen[k] = true + out = append(out, customersSighting(customers.KindHiveUser, user, pred, customers.AuditRef(day), at, customersSourceAudit)) + } + return out +} + +// customersAuditResolver: an audit day exists while it is inside the audit +// log's retention. An audit edge is for the full view only: it says when +// someone worked. +type customersAuditResolver struct{ now func() time.Time } + +func (r customersAuditResolver) Exists(ref string) bool { + day, err := time.Parse(customersAuditDayLayout, customersRefID(ref, customers.RefAudit)) + if err != nil { + return false + } + retention := time.Duration(compliance.BuiltinAuditRetentionDays) * 24 * time.Hour + return r.now().Sub(day) <= retention+24*time.Hour +} + +func (r customersAuditResolver) Visible(_ string, v customers.Viewer) bool { return v.Full } diff --git a/src/cmd/hive/customers_sweep_test.go b/src/cmd/hive/customers_sweep_test.go index a4c364f53e..c56e859e93 100644 --- a/src/cmd/hive/customers_sweep_test.go +++ b/src/cmd/hive/customers_sweep_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "strings" "sync/atomic" "testing" "time" @@ -14,6 +15,7 @@ import ( "github.com/hivecommons/hive/pkg/claims" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/customers" + "github.com/hivecommons/hive/pkg/dashboard" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/inbox" "github.com/hivecommons/hive/pkg/mailallow" @@ -311,3 +313,60 @@ func TestCustomersResolversWithStoresOff(t *testing.T) { } } } + +func TestCustomersAuditSightings(t *testing.T) { + src := customersTestSources() + src.audit = []dashboard.AuditEntry{ + {Timestamp: "2026-11-03T09:00:00Z", User: "olivia", Action: "config_save", Detail: "secret=hunter2"}, + {Timestamp: "2026-11-03T17:00:00Z", User: "Olivia", Action: "agent_restart"}, + {Timestamp: "2026-11-03T08:00:00Z", User: "olivia", Action: "dashboard_login"}, + {Timestamp: "2026-11-04T01:00:00Z", User: "olivia", Action: "pause"}, + {Timestamp: "2026-11-03T09:00:00Z", User: "reed", Action: "customer_edit"}, + {Timestamp: "not a time", User: "reed", Action: "pause"}, + {Timestamp: "2026-11-03T09:00:00Z", User: " ", Action: "pause"}, + } + got := map[sightKey]customers.Sighting{} + for _, s := range customersAuditSightings(src) { + got[sightKey{s.Kind, s.Value, s.Predicate, s.Artefact}] = s + } + want := []sightKey{ + {customers.KindHiveUser, "olivia", customers.PredActed, "audit:2026-11-03"}, + {customers.KindHiveUser, "olivia", customers.PredLoggedIn, "audit:2026-11-03"}, + {customers.KindHiveUser, "olivia", customers.PredActed, "audit:2026-11-04"}, + {customers.KindHiveUser, "reed", customers.PredActed, "audit:2026-11-03"}, + } + if len(got) != len(want) { + t.Fatalf("%d audit sightings, want %d (one per person, kind and day): %v", len(got), len(want), got) + } + for _, k := range want { + if s, ok := got[k]; !ok || s.Source != customersSourceAudit { + t.Errorf("missing audit sighting %+v", k) + } + } + for k := range got { + if strings.Contains(k.ref+k.value, "hunter2") { + t.Fatal("audit detail text was copied") + } + } + if len(customersAuditSightings(customersSources{})) != 0 { + t.Fatal("no audit log, no sightings") + } +} + +func TestCustomersAuditResolver(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + r := customersAuditResolver{now: func() time.Time { return now }} + for ref, want := range map[string]bool{ + "audit:2026-11-17": true, "audit:2026-08-20": true, "audit:2026-08-10": false, "audit:garbage": false, "audit:": false, + } { + if got := r.Exists(ref); got != want { + t.Errorf("Exists(%q) = %v, want %v", ref, got, want) + } + } + if !r.Visible("audit:2026-11-17", customers.Viewer{User: "a", Full: true}) || r.Visible("audit:2026-11-17", customers.Viewer{User: "a"}) { + t.Fatal("audit edges are for the full view only") + } + if (&boot{}).customersResolvers()[customers.RefAudit] == nil { + t.Fatal("the audit resolver is not registered") + } +} diff --git a/src/cmd/hive/customerswire.go b/src/cmd/hive/customerswire.go index b2eb1bf86c..89b9544e17 100644 --- a/src/cmd/hive/customerswire.go +++ b/src/cmd/hive/customerswire.go @@ -160,3 +160,7 @@ func (c *customersDashboard) Graph(ctx context.Context, v dashboard.CustomersVie res := c.graph.Exec(ctx, customersViewer(v), req.Query, req.OperationName, req.Variables) return dashboard.CustomerGraphResult{Body: res.Body, Nodes: res.Nodes, Errors: res.Errors}, nil } + +func (c *customersDashboard) AnswerHint(v dashboard.CustomersViewer, hintID string, same bool) (dashboard.CustomerResult, error) { + return customerResult(c.svc.AnswerHint(customersViewer(v), hintID, same)) +} diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index abc38a4b06..6c0a2356b0 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -23,7 +23,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Inception | [`api-reference/inception.md`](api-reference/inception.md) | 14 | | Beads | [`api-reference/beads.md`](api-reference/beads.md) | 5 | | Sessions | [`api-reference/sessions.md`](api-reference/sessions.md) | 8 | -| Customers | [`api-reference/customers.md`](api-reference/customers.md) | 8 | +| Customers | [`api-reference/customers.md`](api-reference/customers.md) | 9 | | Dashboard miscellaneous | [`api-reference/dashboard-misc.md`](api-reference/dashboard-misc.md) | 56 | | Hub SaaS | [`api-reference/hub-saas.md`](api-reference/hub-saas.md) | 102 | | Hub server | [`api-reference/hub-server.md`](api-reference/hub-server.md) | 46 | @@ -82,7 +82,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh ## Customers -8 routes — see [api-reference/customers.md](api-reference/customers.md). +9 routes — see [api-reference/customers.md](api-reference/customers.md). ## Dashboard miscellaneous diff --git a/src/docs/api-reference/customers.md b/src/docs/api-reference/customers.md index f1e85e0c7a..0442b88abc 100644 --- a/src/docs/api-reference/customers.md +++ b/src/docs/api-reference/customers.md @@ -12,13 +12,14 @@ The rules are enforced twice: by the handlers and again by the store's service o | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/customers` | Signed-in user | The Customers section: `{enabled, full, owner, me, people, suggestions, default_tags, levels}`. `me` is the viewer's own profile, created on first read. `people` and `suggestions` are empty without the full view | `pkg/dashboard/api_customers.go:132` | -| `POST` | `/api/customers` | Full view | Add a customer by hand: `{name, identities?: [{kind, value}]}`. 409 when an identity belongs to another customer; a `hive_user` identity is refused. Audited as `customer_add` | `pkg/dashboard/api_customers.go:133` | -| `GET` | `/api/customers/{id}` | Signed-in user; self reaches only `me` | One profile, with edge counts and open "Same person?" hints for the full view. A viewer without the full view gets no notes, satisfaction, merge history, counts or hints. Opening someone else's profile is audited as `customer_profile_open` | `pkg/dashboard/api_customers.go:134` | -| `POST` | `/api/customers/{id}/edit` | Full view; self only as `/api/customers/me/edit` | One change: `{op, ...}` with `op` one of `name`, `notes`, `identity_add` (`kind`, `value`), `identity_remove` (`key`), `tag` (`tag`, `state` of `on`, `off` or `auto`), `goal_add` (`text`), `goal_edit` (`goal_id`, `text`), `goal_confirm`, `goal_reject` (`goal_id`), `satisfaction_set` (`level`), `satisfaction_confirm`, `satisfaction_reject`. Self may use the name, identity, tag and goal ops; an identity added by self is an unconfirmed claim that resolves nobody until the full view confirms it with `identity_add`. Audited as `customer_edit` with the person and the op, never the value | `pkg/dashboard/api_customers.go:135` | -| `DELETE` | `/api/customers/{id}` | Owner only | Forget: deletes the customer, their identities and every edge to them, and keeps one salted-hash tombstone per confirmed identity so discovery does not rebuild them. 200 `{forgotten, edges_removed}`. Audited as `customer_forget` | `pkg/dashboard/api_customers.go:136` | -| `POST` | `/api/customers/suggestions/{sid}/accept` | Full view | Turn a suggested person into a customer. Audited as `customer_accept` | `pkg/dashboard/api_customers.go:137` | -| `POST` | `/api/customers/suggestions/{sid}/dismiss` | Full view | Delete a suggestion and tombstone its key, so it is not offered again. Audited as `customer_dismiss` | `pkg/dashboard/api_customers.go:138` | +| `GET` | `/api/customers` | Signed-in user | The Customers section: `{enabled, full, owner, me, people, suggestions, default_tags, levels}`. `me` is the viewer's own profile, created on first read. `people` and `suggestions` are empty without the full view | `pkg/dashboard/api_customers.go:141` | +| `POST` | `/api/customers` | Full view | Add a customer by hand: `{name, identities?: [{kind, value}]}`. 409 when an identity belongs to another customer; a `hive_user` identity is refused. Audited as `customer_add` | `pkg/dashboard/api_customers.go:142` | +| `GET` | `/api/customers/{id}` | Signed-in user; self reaches only `me` | One profile, with edge counts and open "Same person?" hints for the full view. A viewer without the full view gets no notes, satisfaction, merge history, counts or hints. Opening someone else's profile is audited as `customer_profile_open` | `pkg/dashboard/api_customers.go:143` | +| `POST` | `/api/customers/{id}/edit` | Full view; self only as `/api/customers/me/edit` | One change: `{op, ...}` with `op` one of `name`, `notes`, `identity_add` (`kind`, `value`), `identity_remove` (`key`), `tag` (`tag`, `state` of `on`, `off` or `auto`), `goal_add` (`text`), `goal_edit` (`goal_id`, `text`), `goal_confirm`, `goal_reject` (`goal_id`), `satisfaction_set` (`level`), `satisfaction_confirm`, `satisfaction_reject`. Self may use the name, identity, tag and goal ops; an identity added by self is an unconfirmed claim that resolves nobody until the full view confirms it with `identity_add`. Audited as `customer_edit` with the person and the op, never the value | `pkg/dashboard/api_customers.go:144` | +| `DELETE` | `/api/customers/{id}` | Owner only | Forget: deletes the customer, their identities and every edge to them, and keeps one salted-hash tombstone per confirmed identity so discovery does not rebuild them. 200 `{forgotten, edges_removed}`. Audited as `customer_forget` | `pkg/dashboard/api_customers.go:145` | +| `POST` | `/api/customers/suggestions/{sid}/accept` | Full view | Turn a suggested person into a customer. Audited as `customer_accept` | `pkg/dashboard/api_customers.go:146` | +| `POST` | `/api/customers/suggestions/{sid}/dismiss` | Full view | Delete a suggestion and tombstone its key, so it is not offered again. Audited as `customer_dismiss` | `pkg/dashboard/api_customers.go:147` | +| `POST` | `/api/customers/hints/{hid}/answer` | Full view | Answer a "Same person?" question: `{same}`. `true` makes the suggested identity the customer's own and deletes the suggestion; `false` closes the question for good. A question between two customers is answered by merging them, so `true` on one is 400. Audited as `customer_hint_answer` | `pkg/dashboard/api_customers.go:148` | | `POST` | `/api/graph` | Signed-in user | The customer graph over GraphQL, read-only (no mutations, so a read-only user may call it): `{query, operationName?, variables?}`, answered with a GraphQL `{data, errors}` document. Access follows the viewer exactly as above; see [the customer graph](#the-customer-graph). Audited as `customer_graph_query` with the operation name, node count and error count, never the query text | `pkg/dashboard/api_graph.go:47` | ## The customer graph diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 37ddded102..a7bfa380f5 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -219,7 +219,7 @@ Opening a profile shows: - **Satisfaction** (owner and read-write only): a level (Unknown, At risk, Neutral, Satisfied) with what led to it. There is no score. Hive may suggest a level; it never changes one a person set. - **Tags**: click a tag to turn it on or off. A tag marked manual stays as set; **Reset to automatic** hands it back to hive. - **Identities**: the logins, addresses and ids the person is known by. An identity a read-only user adds to their own profile is shown as unconfirmed, and does nothing, until the owner or a read-write user presses **Confirm**. The hive user identity cannot be changed. -- **Activity** and **Notes** (owner and read-write only). The person does not see the notes. +- **Activity** and **Notes** (owner and read-write only). Activity also shows open "Same person?" questions: hive spots a suggested address or login that looks like one of this customer's. **Yes** makes it theirs; **No** closes the question for good. Nothing is linked until you answer. The person does not see the notes. - **Forget** (owner only): deletes the person, their identities and their activity links, and stops hive rebuilding the profile. Nothing in this section leaves the hive. Turn it off with **Settings › Features › Customers** (`customers.enabled`), which takes effect when the hive restarts. API: [customers](api-reference/customers.md). Design: [customers](design/customers.md). diff --git a/src/docs/design/customers.md b/src/docs/design/customers.md index 6d70a632b5..0ed1847994 100644 --- a/src/docs/design/customers.md +++ b/src/docs/design/customers.md @@ -281,6 +281,27 @@ a new accessor. The sweep is an optional sweep, so it is shed with the other optional sweeps when the GitHub budget is low, although it spends none of that budget itself. +Step D, in the same sweep: the dashboard audit log gives one `acted` edge per +person per day, and one `logged_in` edge on a day they signed in. Only the user, +the day and the kind of action are read; the detail text of an audit line is +never copied. An audit edge exists while its day is inside the audit log's +retention (90 days) and is shown to the full view only. + +"Same person?" hints are raised between a customer and a suggested person when +a suggested address starts like one of the customer's logins (a GitHub login or +the dashboard user name), or a suggested login starts like one of the customer's +addresses. The comparison is on exact, lower-cased keys with any `+tag` removed. +Locals shorter than four characters and role addresses such as `info` or +`noreply` are skipped. A display name is never compared. A hint links nothing: +answering yes makes the suggested identity the customer's own (recorded as +manual, by whom), answering no pins the pair so it is not asked again. A hint +between two customers is answered by merging them, which is the merge and split +UI of a later PR. + +Step E, the budgeted GitHub search for mentions and comments on accept, is not +built. The GitHub client has no comment or mention search, so it needs a new +client method and a place in the API budget. It is left for its own PR. + Automatic tags come from role, association and history: `maintainer` from an owner or merger role or a GitHub author association of owner, member or collaborator; `contributor` from an authored pull request; `end-user` from a diff --git a/src/docs/security-model.md b/src/docs/security-model.md index 24dfb02fe8..488f925393 100644 --- a/src/docs/security-model.md +++ b/src/docs/security-model.md @@ -183,6 +183,29 @@ address (any private, loopback, link-local, CGNAT, multicast, ULA or metadata answer refuses the link), every redirect re-checked (at most 3), the body size- and time-capped, and the environment proxy never used. +### Customers: people the hive has seen + +The Customers section keeps one profile per person. It lives in two files on the +hive's own volume and nothing in it leaves the hive. It is not sent to the hub, +written to GitHub or put in a heartbeat. The design is in +[customers](design/customers.md). + +Some of these people never signed up. They are issue authors, meeting guests and +mail senders. The hive keeps only a key, a few counts and up to five references +for them, and only until someone accepts them. A suggestion ends when the thing +it came from is deleted. Forgetting a person deletes them and leaves a salted +hash, so they are not rebuilt. + +Links between identities are made only on exact keys. A display name never links +anyone. One link rests on an assumption you should know about. When the access +list holds a name such as `github:alice`, the hive treats `alice` as that +person's GitHub login. The hub put that entry there after it signed the person +in with GitHub, so the hive trusts it. If your access list is edited by hand, an +entry like that gives the named person's profile the matching GitHub activity. + +A read-only user sees only their own profile. An identity they add is shown as +unconfirmed. It links nothing until the owner or a read-write user confirms it. + ## 5. Network and credentials **Inference keys.** An agent using a self-hosted inference gateway is diff --git a/src/pkg/customers/hints.go b/src/pkg/customers/hints.go new file mode 100644 index 0000000000..6155fa71e5 --- /dev/null +++ b/src/pkg/customers/hints.go @@ -0,0 +1,183 @@ +package customers + +import ( + "fmt" + "strings" +) + +// "Same person?" hints. A hint is a question for a person to answer; it +// never links anything by itself. The two rules below only ever compare +// exact, normalised keys: a login to the local part of an address. A display +// name is never compared. + +const ( + // minHintLocalLen is the shortest local part or login a hint rule will + // compare. Shorter ones ("bo", "al") match too many unrelated people. + minHintLocalLen = 4 + // hintReasonLocal is the reason a hint carries when an address's local + // part equals a login. + hintReasonLocal = "the address and the login start the same" +) + +// genericLocals are address local parts that name a role, not a person. +var genericLocals = map[string]bool{ + "info": true, "admin": true, "root": true, "support": true, "noreply": true, "no-reply": true, + "contact": true, "hello": true, "team": true, "mail": true, "sales": true, "office": true, + "security": true, "postmaster": true, "webmaster": true, "billing": true, "help": true, +} + +// localPart is the part of an address before the "@" with any "+tag" +// removed, lower-cased. It is "" for anything that is not an address. +func localPart(addr string) string { + l, _, ok := strings.Cut(strings.ToLower(strings.TrimSpace(addr)), "@") + if !ok { + return "" + } + l, _, _ = strings.Cut(l, "+") + return l +} + +func hintableLocal(s string) bool { return len(s) >= minHintLocalLen && !genericLocals[s] } + +// personLogins is the logins a customer is known by: GitHub logins and the +// dashboard user name. +func personLogins(p Person) []string { + var out []string + for _, i := range p.Identities { + if i.Claimed { + continue + } + switch i.Kind { + case KindGitHub, KindHiveUser: + out = append(out, i.Value) + } + } + return out +} + +// personLocals is the local parts of the addresses a customer holds. +func personLocals(p Person) []string { + var out []string + for _, i := range p.Identities { + if i.Claimed { + continue + } + if i.Kind == KindEmail || i.Kind == KindGitEmail { + if l := localPart(i.Value); l != "" { + out = append(out, l) + } + } + } + return out +} + +// DeriveHints raises a "Same person?" question between a customer and a +// suggested person when the suggestion's address starts like one of the +// customer's logins, or the suggestion's login is the start of one of the +// customer's addresses. It returns how many new hints were raised. A pair a +// person said is different is not raised again. +func (s *Store) DeriveHints() (int, error) { + added := 0 + err := s.change(func() error { + added = 0 + for _, sg := range s.sugg { + var local string + switch sg.Kind { + case KindEmail, KindGitEmail: + local = localPart(sg.Value) + case KindGitHub: + local = strings.ToLower(sg.Value) + default: + continue + } + if !hintableLocal(local) { + continue + } + for _, p := range s.people { + match := false + if sg.Kind == KindGitHub { + for _, l := range personLocals(p) { + match = match || l == local + } + } else { + for _, l := range personLogins(p) { + match = match || strings.ToLower(l) == local + } + } + if !match { + continue + } + before := len(s.hints) + h, err := s.addHintLocked(Hint{Person: p.ID, Other: sg.ID, Reason: hintReasonLocal}) + if err != nil { + return err + } + if h != nil && len(s.hints) > before { + added++ + } + } + } + return nil + }) + return added, err +} + +// SuggestionByID returns a suggestion by its id. +func (s *Store) SuggestionByID(id string) (Suggestion, bool) { + s.mu.Lock() + defer s.mu.Unlock() + key, ok := s.suggestionKeyLocked(id) + if !ok { + return Suggestion{}, false + } + return cloneSuggestion(s.sugg[key]), true +} + +// HintByID returns one open hint. +func (s *Store) HintByID(id string) (Hint, bool) { + for _, h := range s.Hints("") { + if h.ID == id { + return h, true + } + } + return Hint{}, false +} + +// AbsorbSuggestion answers a hint "yes, the same person": the suggested +// identity becomes an identity of the customer, the suggestion is deleted +// and every hint about it is closed. The next sweep writes the edges. It is +// refused when the identity already belongs to someone. +func (s *Store) AbsorbSuggestion(personID, suggestionID, by string) (Person, error) { + var out Person + err := s.change(func() error { + p, ok := s.people[personID] + if !ok { + return ErrNotFound + } + key, ok := s.suggestionKeyLocked(suggestionID) + if !ok { + return ErrNotFound + } + sg := s.sugg[key] + if owner, taken := s.owner[key]; taken && owner != personID { + return fmt.Errorf("%w: %s already belongs to another customer", ErrConflict, key) + } + if len(p.Identities) >= MaxIdentities { + return fmt.Errorf("%w: too many identities", ErrInvalid) + } + now := s.now().UTC() + if !p.HasIdentity(key) { + p.Identities = append(p.Identities, Identity{ + Kind: sg.Kind, Value: sg.Value, Source: "same_person_hint", Confidence: 1, Manual: true, At: now, By: by, + }) + } + p.UpdatedAt = now + s.people[personID] = p + s.unpinLocked(PinUnlink, key, personID) + delete(s.sugg, key) + s.dropRefsLocked(suggestionID) + out = clonePerson(p) + return nil + }) + return out, err +} diff --git a/src/pkg/customers/hints_test.go b/src/pkg/customers/hints_test.go new file mode 100644 index 0000000000..c8ba2c5b23 --- /dev/null +++ b/src/pkg/customers/hints_test.go @@ -0,0 +1,180 @@ +package customers + +import ( + "errors" + "testing" +) + +func TestLocalPart(t *testing.T) { + for in, want := range map[string]string{ + "Ada.Lovelace+news@Example.com": "ada.lovelace", "bob@x.io": "bob", "no-at-sign": "", "": "", + } { + if got := localPart(in); got != want { + t.Errorf("localPart(%q) = %q, want %q", in, got, want) + } + } + for s, want := range map[string]bool{"octocat": true, "bo": false, "info": false, "admin": false, "noreply": false} { + if hintableLocal(s) != want { + t.Errorf("hintableLocal(%q) = %v", s, !want) + } + } +} + +func seedSuggestion(t *testing.T, s *Store, kind IdentityKind, value string) Suggestion { + t.Helper() + if _, err := s.Observe([]Observation{{Kind: kind, Value: value, Predicate: PredSent, Artefact: InboxRef("email", value)}}); err != nil { + t.Fatal(err) + } + sg, ok := s.SuggestionByID(s.Suggestions()[0].ID) + for _, c := range s.Suggestions() { + if c.Value == NormalizeIdentity(kind, value) { + sg, ok = c, true + } + } + if !ok { + t.Fatal("no suggestion") + } + return sg +} + +func TestDeriveHintsComparesKeysNeverNames(t *testing.T) { + s := openStore(t) + octo := mustAdd(t, s, "Some Display Name", Identity{Kind: KindGitHub, Value: "octocat"}) + mustAdd(t, s, "Short", Identity{Kind: KindGitHub, Value: "bo"}) + byMail := mustAdd(t, s, "Mail Person", Identity{Kind: KindEmail, Value: "dana.reyes@example.com"}) + mail := seedSuggestion(t, s, KindEmail, "Octocat+news@Example.org") + seedSuggestion(t, s, KindEmail, "bo@example.org") // too short to compare + seedSuggestion(t, s, KindEmail, "info@octocat-corp.com") // role address + seedSuggestion(t, s, KindEmail, "someone.else@example.org") // matches no login + login := seedSuggestion(t, s, KindGitHub, "Dana.Reyes") + // A name never raises a hint, even an exact match for a customer's name. + if _, err := s.Observe([]Observation{{Kind: KindName, Value: "Some Display Name", Predicate: PredAttended, Artefact: MeetingRef("m1")}}); err != nil { + t.Fatal(err) + } + + n, err := s.DeriveHints() + if err != nil || n != 2 { + t.Fatalf("DeriveHints = %d, %v; want 2", n, err) + } + hints := s.Hints("") + got := map[string]string{} + for _, h := range hints { + got[h.Person] = h.Other + if h.Reason == "" || h.Identity != nil { + t.Fatalf("hint = %+v", h) + } + } + if got[octo.ID] != mail.ID || got[byMail.ID] != login.ID || len(got) != 2 { + t.Fatalf("hints = %v, want octocat<->mail and dana<->login", got) + } + // Raised once: running again adds nothing. + if n, _ := s.DeriveHints(); n != 0 || len(s.Hints("")) != 2 { + t.Fatalf("second DeriveHints = %d, %d open", n, len(s.Hints(""))) + } + // A hint links nothing. + if _, ok := s.Lookup(KindEmail, "octocat+news@example.org"); ok { + t.Fatal("a hint linked an identity") + } +} + +func TestAnswerHintYesAbsorbsTheSuggestion(t *testing.T) { + s := newService(t) + st := s.Store() + octo := mustAdd(t, st, "Octo", Identity{Kind: KindGitHub, Value: "octocat"}) + mail := seedSuggestion(t, st, KindEmail, "octocat@example.org") + if _, err := st.DeriveHints(); err != nil { + t.Fatal(err) + } + h := st.Hints(octo.ID)[0] + + view, err := s.Get(ownerV, octo.ID) + if err != nil || len(view.Hints) != 1 || view.Hints[0].OtherKind != "email" || view.Hints[0].OtherValue != "octocat@example.org" || view.Hints[0].ID != h.ID { + t.Fatalf("hint view = %+v, %v", view.Hints, err) + } + if _, err := s.AnswerHint(readV, h.ID, true); !errors.Is(err, ErrForbidden) { + t.Fatalf("read-only AnswerHint = %v", err) + } + if _, err := s.AnswerHint(ownerV, "h_missing", true); !errors.Is(err, ErrNotFound) { + t.Fatalf("missing hint = %v", err) + } + got, err := s.AnswerHint(rwV, h.ID, true) + if err != nil || !got.HasIdentity("email:octocat@example.org") { + t.Fatalf("AnswerHint yes = %+v, %v", got, err) + } + for _, i := range got.Identities { + if i.Kind == KindEmail && (!i.Manual || i.By != "rita" || i.Source != "same_person_hint") { + t.Fatalf("absorbed identity = %+v", i) + } + } + if _, ok := st.SuggestionByID(mail.ID); ok || len(st.Hints("")) != 0 { + t.Fatal("the suggestion or its hint survived the answer") + } + // Now it is a key: later sightings are the customer's activity. + owners, _ := st.Observe([]Observation{{Kind: KindEmail, Value: "octocat@example.org", Predicate: PredSent, Artefact: InboxRef("email", "m9")}}) + if owners[0] != octo.ID || len(st.Suggestions()) != 0 { + t.Fatalf("owners = %v, suggestions %d", owners, len(st.Suggestions())) + } +} + +func TestAnswerHintNoPinsThePair(t *testing.T) { + s := newService(t) + st := s.Store() + octo := mustAdd(t, st, "Octo", Identity{Kind: KindGitHub, Value: "octocat"}) + seedSuggestion(t, st, KindEmail, "octocat@example.org") + if _, err := st.DeriveHints(); err != nil { + t.Fatal(err) + } + h := st.Hints(octo.ID)[0] + got, err := s.AnswerHint(ownerV, h.ID, false) + if err != nil || got.ID != octo.ID || got.HasIdentity("email:octocat@example.org") { + t.Fatalf("AnswerHint no = %+v, %v", got, err) + } + if n, _ := st.DeriveHints(); n != 0 || len(st.Hints("")) != 0 { + t.Fatalf("a rejected pair was asked again: %d", n) + } + if len(st.Suggestions()) != 1 { + t.Fatal("answering no must leave the suggestion for someone to accept or dismiss") + } +} + +func TestAbsorbSuggestionRefusals(t *testing.T) { + s := openStore(t) + a := mustAdd(t, s, "A", Identity{Kind: KindGitHub, Value: "alphaone"}) + sg := seedSuggestion(t, s, KindEmail, "alphaone@example.org") + if _, err := s.AbsorbSuggestion("p_missing", sg.ID, "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("missing person = %v", err) + } + if _, err := s.AbsorbSuggestion(a.ID, "s_missing", "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("missing suggestion = %v", err) + } + // Someone else takes the address by hand first: absorbing is refused. + other := mustAdd(t, s, "B") + if _, err := s.Accept(sg.ID, "owner"); err != nil { + t.Fatal(err) + } + if _, err := s.AbsorbSuggestion(other.ID, sg.ID, "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("a suggestion that was accepted is gone: %v", err) + } + // Accepting closed the hints that named the suggestion. + if _, err := s.Accept(seedSuggestion(t, s, KindEmail, "alphaone@elsewhere.org").ID, "owner"); err != nil { + t.Fatal(err) + } +} + +func TestAnswerHintBetweenCustomersAsksForAMerge(t *testing.T) { + s := newService(t) + st := s.Store() + a := mustAdd(t, st, "A") + b := mustAdd(t, st, "B") + if err := st.AddHint(a.ID, b.ID, "same"); err != nil { + t.Fatal(err) + } + h := st.Hints(a.ID)[0] + if _, err := s.AnswerHint(ownerV, h.ID, true); !errors.Is(err, ErrInvalid) { + t.Fatalf("a customer-to-customer yes = %v, want ErrInvalid", err) + } + view, _ := s.Get(ownerV, a.ID) + if view.Hints[0].OtherKind != "customer" || view.Hints[0].OtherValue != "B" { + t.Fatalf("hint view = %+v", view.Hints) + } +} diff --git a/src/pkg/customers/ingest.go b/src/pkg/customers/ingest.go index e66338e21b..26eed38f9b 100644 --- a/src/pkg/customers/ingest.go +++ b/src/pkg/customers/ingest.go @@ -67,6 +67,7 @@ type SweepResult struct { PrunedEdges int `json:"pruned_edges"` ExpiredSuggestions int `json:"expired_suggestions"` DroppedEvidence int `json:"dropped_evidence"` + Hints int `json:"hints"` } // Sweep runs one discovery pass. It is safe to run repeatedly: the same @@ -162,6 +163,9 @@ func (s *Service) Sweep(in SweepInput) (SweepResult, error) { return res, err } res.Suggestions = len(s.store.Suggestions()) + if res.Hints, err = s.store.DeriveHints(); err != nil { + return res, err + } // Automatic tags, from role, association and history. A manual tag is // never touched. diff --git a/src/pkg/customers/resolve.go b/src/pkg/customers/resolve.go index 7dc1ece473..b80fd75cee 100644 --- a/src/pkg/customers/resolve.go +++ b/src/pkg/customers/resolve.go @@ -504,6 +504,7 @@ func (s *Store) Accept(suggestionID, by string) (Person, error) { CreatedAt: now, UpdatedAt: now, } delete(s.sugg, key) + s.dropRefsLocked(suggestionID) s.people[pid] = p out = clonePerson(p) return nil diff --git a/src/pkg/customers/service.go b/src/pkg/customers/service.go index 4856229884..6660d668a6 100644 --- a/src/pkg/customers/service.go +++ b/src/pkg/customers/service.go @@ -69,7 +69,7 @@ type PersonView struct { Counts map[string]int `json:"counts,omitempty"` // Hints are the open "Same person?" questions. Full view only: a hint // names another profile. - Hints []Hint `json:"hints,omitempty"` + Hints []HintView `json:"hints,omitempty"` // Hinted reports that the last identity edit was not linked because // the identity belongs to someone else, and was raised as a question // instead. @@ -160,7 +160,9 @@ func (s *Service) view(v Viewer, p Person, isMe, detail bool) PersonView { return out } if detail { - out.Hints = s.store.Hints(p.ID) + for _, h := range s.store.Hints(p.ID) { + out.Hints = append(out.Hints, s.hintView(h)) + } if s.index != nil { if counts, err := s.index.Counts(p.ID); err == nil && len(counts) > 0 { out.Counts = counts @@ -396,3 +398,54 @@ func (s *Service) ArtefactPeople(v Viewer, ref string, limit int) ([]ArtefactPer } return out, nil } + +// HintView is a hint with what it asks about spelled out, so a person can +// answer it without opening another profile. For a suggested person that is +// the suggestion's identity; for a customer, their name. +type HintView struct { + Hint + OtherKind string `json:"other_kind,omitempty"` + OtherValue string `json:"other_value,omitempty"` +} + +func (s *Service) hintView(h Hint) HintView { + v := HintView{Hint: h} + if sg, ok := s.store.SuggestionByID(h.Other); ok { + v.OtherKind, v.OtherValue = string(sg.Kind), sg.Value + } else if p, err := s.store.Get(h.Other); err == nil { + v.OtherKind, v.OtherValue = "customer", p.Name + } + return v +} + +// AnswerHint answers a "Same person?" question. Yes makes the suggested +// identity the customer's own; no closes the question and remembers it, so +// it is not asked again. Full view only. A hint between two customers is +// answered by merging them, which is a separate action. +func (s *Service) AnswerHint(v Viewer, hintID string, same bool) (PersonView, error) { + if !v.Full { + return PersonView{}, ErrForbidden + } + h, ok := s.store.HintByID(hintID) + if !ok { + return PersonView{}, ErrNotFound + } + if !same { + if _, err := s.store.ResolveHint(hintID, false, v.User); err != nil { + return PersonView{}, err + } + p, err := s.store.Get(h.Person) + if err != nil { + return PersonView{}, err + } + return s.view(v, p, false, true), nil + } + if _, isSuggestion := s.store.SuggestionByID(h.Other); !isSuggestion { + return PersonView{}, fmt.Errorf("%w: merge the two customers instead", ErrInvalid) + } + p, err := s.store.AbsorbSuggestion(h.Person, h.Other, v.User) + if err != nil { + return PersonView{}, err + } + return s.view(v, p, false, true), nil +} diff --git a/src/pkg/dashboard/api_customers.go b/src/pkg/dashboard/api_customers.go index 28553eeb25..e3719aa3d3 100644 --- a/src/pkg/dashboard/api_customers.go +++ b/src/pkg/dashboard/api_customers.go @@ -110,6 +110,15 @@ type CustomersService interface { Forget(v CustomersViewer, id string) (edges int, err error) Accept(v CustomersViewer, suggestionID string) (CustomerResult, error) Dismiss(v CustomersViewer, suggestionID string) error + // AnswerHint answers a "Same person?" question: same true makes the + // suggested identity the customer's own, false closes the question for + // good. + AnswerHint(v CustomersViewer, hintID string, same bool) (CustomerResult, error) +} + +// CustomerHintAnswer is the body of POST /api/customers/hints/{hid}/answer. +type CustomerHintAnswer struct { + Same bool `json:"same"` } type customersHolder struct{ svc CustomersService } @@ -136,6 +145,7 @@ func (s *Server) registerCustomersRoutes() { s.mux.HandleFunc("DELETE /api/customers/{id}", s.handleCustomersForget) s.mux.HandleFunc("POST /api/customers/suggestions/{sid}/accept", s.handleCustomersAccept) s.mux.HandleFunc("POST /api/customers/suggestions/{sid}/dismiss", s.handleCustomersDismiss) + s.mux.HandleFunc("POST /api/customers/hints/{hid}/answer", s.handleCustomersHintAnswer) s.registerCustomersGraphRoutes() } @@ -382,3 +392,25 @@ func (s *Server) handleCustomersDismiss(w http.ResponseWriter, r *http.Request) s.auditFromRequest(r, "customer_dismiss", auditDetail("suggestion", sid), "") jsonResponse(w, map[string]any{"dismissed": true}) } + +func (s *Server) handleCustomersHintAnswer(w http.ResponseWriter, r *http.Request) { + v, ok := customersFullViewer(w, r) + if !ok { + return + } + svc, ok := s.customersService(w) + if !ok { + return + } + var body CustomerHintAnswer + if !decodeCustomersBody(w, r, &body) { + return + } + res, err := svc.AnswerHint(v, r.PathValue("hid"), body.Same) + if err != nil { + s.customersError(w, r, err) + return + } + s.auditFromRequest(r, "customer_hint_answer", auditDetail("person", res.ID, "same", boolString(body.Same)), "") + jsonResponse(w, res.View) +} diff --git a/src/pkg/dashboard/api_customers_test.go b/src/pkg/dashboard/api_customers_test.go index 38de4b6928..9e8578d826 100644 --- a/src/pkg/dashboard/api_customers_test.go +++ b/src/pkg/dashboard/api_customers_test.go @@ -64,6 +64,11 @@ func (f *fakeCustomersService) Accept(v CustomersViewer, sid string) (CustomerRe return f.result("p_accepted", v) } +func (f *fakeCustomersService) AnswerHint(v CustomersViewer, hid string, same bool) (CustomerResult, error) { + f.note("AnswerHint", v, fmt.Sprintf("%s:%v", hid, same)) + return f.result("p_hinted", v) +} + func (f *fakeCustomersService) Dismiss(v CustomersViewer, sid string) error { f.note("Dismiss", v, sid) return f.err @@ -121,6 +126,7 @@ var ( custForget = customersRoute{http.MethodDelete, "/api/customers/p_other", ""} custAccept = customersRoute{http.MethodPost, "/api/customers/suggestions/s_1/accept", ""} custDismiss = customersRoute{http.MethodPost, "/api/customers/suggestions/s_1/dismiss", ""} + custHint = customersRoute{http.MethodPost, "/api/customers/hints/h_1/answer", `{"same":true}`} ) // TestCustomersRoleMatrix walks every route as every kind of caller. The @@ -143,6 +149,7 @@ func TestCustomersRoleMatrix(t *testing.T) { {custAdd, map[string]int{"owner": ok, "read-write": ok, "merger": ok, "read": forbidden, "unverified owner": forbidden, "read with no name": forbidden}}, {custAccept, map[string]int{"owner": ok, "read-write": ok, "merger": ok, "read": forbidden, "unverified owner": forbidden, "read with no name": forbidden}}, {custDismiss, map[string]int{"owner": ok, "read-write": ok, "merger": ok, "read": forbidden, "unverified owner": forbidden, "read with no name": forbidden}}, + {custHint, map[string]int{"owner": ok, "read-write": ok, "merger": ok, "read": forbidden, "unverified owner": forbidden, "read with no name": forbidden}}, {custForget, map[string]int{"owner": ok, "read-write": forbidden, "merger": forbidden, "read": forbidden, "unverified owner": forbidden, "read with no name": forbidden}}, } s, _ := apiServer(t) @@ -230,7 +237,7 @@ func TestCustomersOffAndErrors(t *testing.T) { if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &off) != nil || off["enabled"] != false { t.Fatalf("list while off = %d %s", rec.Code, rec.Body.String()) } - for _, r := range []customersRoute{custGetMe, custEditMe, custAdd, custForget, custAccept, custDismiss} { + for _, r := range []customersRoute{custGetMe, custEditMe, custAdd, custForget, custAccept, custDismiss, custHint} { if rec := customersDo(s, custOwner, r.method, r.path, r.body); rec.Code != http.StatusServiceUnavailable { t.Errorf("%s %s while off = %d, want 503", r.method, r.path, rec.Code) } @@ -287,6 +294,7 @@ func TestCustomersAudit(t *testing.T) { {custReadWrite, custEditOther}, {custReadWrite, custAccept}, {custReadWrite, custDismiss}, + {custReadWrite, custHint}, {custOwner, custForget}, } for _, st := range steps { @@ -302,8 +310,8 @@ func TestCustomersAudit(t *testing.T) { count++ } } - if count != 7 { - t.Fatalf("audited %d customer actions, want 7: %v", count, got) + if count != 8 { + t.Fatalf("audited %d customer actions, want 8: %v", count, got) } want := map[string]string{ "customer_profile_open": "olivia|person=p_other;", @@ -311,6 +319,7 @@ func TestCustomersAudit(t *testing.T) { "customer_forget": "olivia|person=p_other, edges=3;", "customer_accept": "rita|person=p_accepted;", "customer_dismiss": "rita|suggestion=s_1;", + "customer_hint_answer": "rita|person=p_hinted, same=true;", } for action, detail := range want { if got[action] != detail { diff --git a/src/pkg/dashboard/customers_ui_test.go b/src/pkg/dashboard/customers_ui_test.go index a2765e2762..67fcceb72a 100644 --- a/src/pkg/dashboard/customers_ui_test.go +++ b/src/pkg/dashboard/customers_ui_test.go @@ -51,6 +51,7 @@ func TestCustomersSectionWiring(t *testing.T) { `data-action="customersSatisfactionReject"`, `data-action="customersIdentityConfirm"`, `data-action="customersForget"`, + `'/api/customers/hints/' + encodeURIComponent(hid) + '/answer'`, `customersRequest('POST', '/api/graph', { query: CUSTOMERS_TIMELINE_QUERY, operationName: 'Timeline', variables: variables })`, `person(id: $id) { edges(first: $first, after: $after) { nodes { predicate at source artefact { ref kind } } next } }`, `Reset to automatic`, @@ -83,7 +84,7 @@ func TestCustomersViewGates(t *testing.T) { "customersAddFormHtml", "customersListHtml", "customersIdentityRowHtml", "customersIdentitiesHtml", "customersTagChipHtml", "customersTagsHtml", "customersGoalRowHtml", "customersGoalsHtml", "customersSatisfactionHtml", "customersNotesHtml", "customersActivityHtml", "customersForgetHtml", "customersProfileHtml", "customersFormatTime", - "customersTimelineGroups", "customersTimelineRowHtml", "customersTimelineHtml", + "customersTimelineGroups", "customersTimelineRowHtml", "customersTimelineHtml", "customersHintRowHtml", } { fns = append(fns, jsFunc(t, html, name)) } @@ -104,7 +105,7 @@ const person = { tags: [{ name: 'maintainer', state: 'on', source: 'auto', rule: 'role:owner' }, { name: 'vip', state: 'on', source: 'manual', by: 'olivia' }, { name: 'end-user', state: 'off', source: 'auto' }], goals: [{ id: 'g_1', text: 'Ship exports', state: 'confirmed', source: 'manual', by: 'ada' }, { id: 'g_2', text: 'Wants SSO', state: 'suggested', source: 'auto', evidence: ['gh:issue:o/r#1'] }], satisfaction: { level: 'at_risk', source: 'manual', by: 'olivia', suggestion: { level: 'neutral', evidence: ['gh:pr:o/r#2'] } }, - counts: { authored: 3 }, hints: [{ id: 'h_1' }] + counts: { authored: 3 }, hints: [{ id: 'h_1', other_kind: 'email', other_value: 'ada@.org', reason: 'the address and the login start the same' }, { id: 'h_2', other_kind: 'customer', other_value: 'Ada B' }] }; const base = { enabled: true, me: Object.assign({}, person, { id: 'p_me', me: true, name: 'Me' }), people: [person], suggestions: [{ id: 's_1', kind: 'github', value: 'stranger', counts: { authored: 2 }, evidence: ['gh:issue:o/r#9'] }], default_tags: ['maintainer', 'contributor', 'end-user', 'stakeholder'], levels: ['unknown', 'at_risk', 'neutral', 'satisfied'] }; @@ -118,6 +119,8 @@ must(!list.includes('Ada') && list.includes('<b>Ada</b>'), 'a must(prof.includes('data-action="customersForget"'), 'owner profile lacks Forget'); must(prof.includes('data-action="customersSatisfactionSet"') && prof.includes('data-action="customersSatisfactionConfirm"') && prof.includes('private note'), 'owner profile lacks satisfaction or notes'); must(prof.includes('data-action="customersIdentityConfirm"'), 'owner cannot confirm a claimed identity'); +must(prof.includes('data-action="customersHintAnswer" data-arg0="h_1" data-arg1="yes"') && prof.includes('data-arg0="h_1" data-arg1="no"') && prof.includes('ada@<x>.org'), 'a suggested-identity hint lacks Yes, No or an escaped identity'); +must(!prof.includes('data-arg0="h_2" data-arg1="yes"') && prof.includes('data-arg0="h_2" data-arg1="no"'), 'a customer-to-customer hint offers Yes'); must(prof.includes('data-action="customersGoalConfirm" data-arg0="g_2"') && prof.includes('gh:issue:o/r#1'), 'a suggested goal lacks Confirm or its evidence'); must(!prof.includes('data-action="customersGoalConfirm" data-arg0="g_1"'), 'a confirmed goal offers Confirm'); must(prof.includes('data-arg0="vip" data-arg1="auto"') && !prof.includes('data-arg0="maintainer" data-arg1="auto"'), 'Reset to automatic must show on manual tags only'); diff --git a/src/pkg/dashboard/static-src/js/customers.js b/src/pkg/dashboard/static-src/js/customers.js index 010c8e5d9d..024525fec7 100644 --- a/src/pkg/dashboard/static-src/js/customers.js +++ b/src/pkg/dashboard/static-src/js/customers.js @@ -305,6 +305,18 @@ (t.next ? '
' : ''); } + // A "Same person?" hint names a suggested identity that may belong to this + // customer. Yes makes it theirs; No closes the question for good. A hint + // between two customers is answered by merging them, so it has no Yes here. + function customersHintRowHtml(h) { + const id = escapeHtml(h.id); + const what = h.other_kind === 'customer' ? 'the customer ' + (h.other_value || '') : (CUSTOMERS_KIND_LABELS[h.other_kind] || h.other_kind || '') + ' ' + (h.other_value || ''); + const yes = h.other_kind === 'customer' ? '' : ''; + return '
Same person? ' + escapeHtml(what.trim()) + '
' + + '
' + escapeHtml(h.reason || '') + '. Nothing is linked until you answer.
' + yes + + '
'; + } + function customersActivityHtml(p) { if (!customersIsFull()) return ''; const counts = p.counts || {}; @@ -313,7 +325,7 @@ return '
' + (keys.length ? '
' + keys.map(k => '' + escapeHtml(k.replace(/_/g, ' ')) + ' ' + counts[k] + '').join('') + '
' : '') + '
' + customersTimelineHtml() + '
' + - (hints.length ? '

' + hints.length + ' open "Same person?" question' + (hints.length === 1 ? '' : 's') + ' about this profile.

' : '') + '
'; + (hints.length ? '
' + hints.map(customersHintRowHtml).join('') + '
' : '') + ''; } function customersForgetHtml(p) { @@ -515,6 +527,18 @@ function customersNotesSave() { customersEdit({ op: 'notes', notes: (customersField('notes') || {}).value || '' }, 'Notes saved'); } + // customersHintAnswer answers a "Same person?" question about the open + // profile. Only the owner and read-write users see hints. + async function customersHintAnswer(hid, answer) { + try { + _customersOpen = await customersRequest('POST', '/api/customers/hints/' + encodeURIComponent(hid) + '/answer', { same: answer === 'yes' }); + customersShow(); + showToast(answer === 'yes' ? 'Identity added to this profile' : 'Noted: not the same person', 'success'); + customersTimelineLoad(true); + fetchCustomers(); + } catch (e) { customersProfileError(e.message); } + } + async function customersForget() { if (!_customersOpen) return; const p = _customersOpen; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 66a36dfe79..b305ab423a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -53249,6 +53249,18 @@ (t.next ? '
' : ''); } + // A "Same person?" hint names a suggested identity that may belong to this + // customer. Yes makes it theirs; No closes the question for good. A hint + // between two customers is answered by merging them, so it has no Yes here. + function customersHintRowHtml(h) { + const id = escapeHtml(h.id); + const what = h.other_kind === 'customer' ? 'the customer ' + (h.other_value || '') : (CUSTOMERS_KIND_LABELS[h.other_kind] || h.other_kind || '') + ' ' + (h.other_value || ''); + const yes = h.other_kind === 'customer' ? '' : ''; + return '
Same person? ' + escapeHtml(what.trim()) + '
' + + '
' + escapeHtml(h.reason || '') + '. Nothing is linked until you answer.
' + yes + + '
'; + } + function customersActivityHtml(p) { if (!customersIsFull()) return ''; const counts = p.counts || {}; @@ -53257,7 +53269,7 @@ return '
' + (keys.length ? '
' + keys.map(k => '' + escapeHtml(k.replace(/_/g, ' ')) + ' ' + counts[k] + '').join('') + '
' : '') + '
' + customersTimelineHtml() + '
' + - (hints.length ? '

' + hints.length + ' open "Same person?" question' + (hints.length === 1 ? '' : 's') + ' about this profile.

' : '') + '
'; + (hints.length ? '
' + hints.map(customersHintRowHtml).join('') + '
' : '') + ''; } function customersForgetHtml(p) { @@ -53459,6 +53471,18 @@ function customersNotesSave() { customersEdit({ op: 'notes', notes: (customersField('notes') || {}).value || '' }, 'Notes saved'); } + // customersHintAnswer answers a "Same person?" question about the open + // profile. Only the owner and read-write users see hints. + async function customersHintAnswer(hid, answer) { + try { + _customersOpen = await customersRequest('POST', '/api/customers/hints/' + encodeURIComponent(hid) + '/answer', { same: answer === 'yes' }); + customersShow(); + showToast(answer === 'yes' ? 'Identity added to this profile' : 'Noted: not the same person', 'success'); + customersTimelineLoad(true); + fetchCustomers(); + } catch (e) { customersProfileError(e.message); } + } + async function customersForget() { if (!_customersOpen) return; const p = _customersOpen;