fix(state): attribute identity events to the subject's single org

This commit is contained in:
sam committed 2026-10-25 21:35:19 +11:00
1 parent e2a268aef1
commit daa7ccb249
5 files changed
+137 -22

No files matched your search

@@ -104,6 +104,42 @@ func (q *Queries) GetVisibleIdentity(ctx context.Context, arg GetVisibleIdentity
return i, err
}
const identityAuditOrg = `-- name: IdentityAuditOrg :one
SELECT min(org_id)::text AS org_id
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging
`
// The identity's org, read only when IdentityAuditOrgCount returns one.
func (q *Queries) IdentityAuditOrg(ctx context.Context, identityID string) (string, error) {
row := q.db.QueryRow(ctx, identityAuditOrg, identityID)
var org_id string
err := row.Scan(&org_id)
return org_id, err
}
const identityAuditOrgCount = `-- name: IdentityAuditOrgCount :one
SELECT count(DISTINCT org_id)::int AS org_count
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging
`
// How many distinct orgs one identity belongs to, across memberships and agent
// assignments. Exactly one makes its events attributable to that org; two or
// more mean an event is not attributable to a single org.
func (q *Queries) IdentityAuditOrgCount(ctx context.Context, identityID string) (int32, error) {
row := q.db.QueryRow(ctx, identityAuditOrgCount, identityID)
var org_count int32
err := row.Scan(&org_count)
return org_count, err
}
const insertIdentity = `-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)