@htilabs/platform-common-models 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +135 -0
  2. package/dist/constants/index.cjs +2 -0
  3. package/dist/constants/index.cjs.map +1 -1
  4. package/dist/constants/index.js +2 -0
  5. package/dist/constants/index.js.map +1 -1
  6. package/dist/{cvcEntry-DAuhe0cd.d.cts → cvcEntry-BqAGctqK.d.cts} +36 -36
  7. package/dist/{cvcEntry-DAuhe0cd.d.ts → cvcEntry-BqAGctqK.d.ts} +36 -36
  8. package/dist/{index-1pWiqEBC.d.cts → index-BTqHP4DM.d.cts} +1 -1
  9. package/dist/{index-uz57Fic9.d.ts → index-Dr6GBCoY.d.ts} +1 -1
  10. package/dist/index.cjs +2 -0
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +2 -2
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/models/index.d.cts +2 -2
  17. package/dist/models/index.d.ts +2 -2
  18. package/dist/org-directory/index.cjs +4 -3
  19. package/dist/org-directory/index.cjs.map +1 -1
  20. package/dist/org-directory/index.d.cts +22 -6
  21. package/dist/org-directory/index.d.ts +22 -6
  22. package/dist/org-directory/index.js +4 -3
  23. package/dist/org-directory/index.js.map +1 -1
  24. package/dist/points-of-contact/index.cjs +6 -3
  25. package/dist/points-of-contact/index.cjs.map +1 -1
  26. package/dist/points-of-contact/index.js +6 -3
  27. package/dist/points-of-contact/index.js.map +1 -1
  28. package/dist/schemas/index.d.cts +11 -11
  29. package/dist/schemas/index.d.ts +11 -11
  30. package/dist/share-review/index.cjs +301 -0
  31. package/dist/share-review/index.cjs.map +1 -0
  32. package/dist/share-review/index.d.cts +431 -0
  33. package/dist/share-review/index.d.ts +431 -0
  34. package/dist/share-review/index.js +263 -0
  35. package/dist/share-review/index.js.map +1 -0
  36. package/package.json +11 -1
  37. package/src/__sot__/README.md +2 -0
  38. package/src/__sot__/captureConflictSemantics.pin.json +156 -0
  39. package/src/generated/captureConflictSemantics.ts +200 -0
  40. package/src/orgDirectory/__tests__/orgDirectory.test.ts +60 -0
  41. package/src/orgDirectory/rules.ts +26 -9
  42. package/src/pointsOfContact/__tests__/writer.test.ts +15 -0
  43. package/src/shareReview/__tests__/captureConflictSemantics.test.ts +148 -0
  44. package/src/shareReview/__tests__/captureConflictSemanticsPin.test.ts +78 -0
  45. package/src/shareReview/__tests__/recommendedDecision.test.ts +35 -0
  46. package/src/shareReview/__tests__/reviewDecision.test.ts +102 -0
  47. package/src/shareReview/__tests__/shareFieldReviewPlan.test.ts +523 -0
  48. package/src/shareReview/captureConflictSemantics.ts +170 -0
  49. package/src/shareReview/index.ts +23 -0
  50. package/src/shareReview/recommendedDecision.ts +21 -0
  51. package/src/shareReview/reviewDecision.ts +71 -0
  52. package/src/shareReview/shareFieldReviewPlan.ts +288 -0
@@ -0,0 +1,170 @@
1
+ import {
2
+ CAPTURE_CONFLICT_SEMANTICS_BY_FIELD,
3
+ type CaptureConflictSemantics,
4
+ } from "../generated/captureConflictSemantics.js";
5
+
6
+ /**
7
+ * The CAPTURE CONFLICT SEMANTICS axis of an inbound CaseShare review.
8
+ *
9
+ * Lifted from pave-2.0 packages/domain/src/captureConflictSemantics.ts @ 312943078
10
+ * (th-hbo9t.2, Thread ADR-THREAD-CASESHARE-INBOUND-REVIEW D-b / D-e) and RE-KEYED:
11
+ * PAVE looked semantics up by its `assertion_domain`; this kernel looks them up by
12
+ * the hti-features registry FIELD id (`capture.living_situation`, …), the key the
13
+ * registry authors at and the prototype's `window.HTI_CAPTURE_CONFLICT_SEMANTICS`
14
+ * block carries. A consumer maps its own carried fields to registry ids (Thread:
15
+ * the D-e differ table); the kernel never sees an app's field names.
16
+ *
17
+ * Answers ONE question, for one captured field: when the sender's value and the
18
+ * recipient's value disagree, what is the reviewer allowed to choose?
19
+ *
20
+ * ## UNAUTHORED IS NOT A VALUE
21
+ *
22
+ * The registry key is OPTIONAL and captured-rows-only, so for most captured
23
+ * fields NOBODY HAS RULED (the counts are in `CAPTURE_CONFLICT_SEMANTICS_SOURCE`).
24
+ * That is a distinct fact from every member of the vocabulary.
25
+ * {@link resolvedSemantics} therefore always reports `authored` alongside the
26
+ * value, and labels the fallback by `rulePath` rather than presenting it as a
27
+ * ruling.
28
+ *
29
+ * The fallback is `single_value_keep_replace`, which is not a guess: it is the
30
+ * prototype's own observed fallback. Its conflict-row render branches on
31
+ * `semantics === "log_end_date_current"` and gives EVERY other value the
32
+ * keep/replace pair (canon c2b0b8b0 `conflictRowHtml`, L351609-L351615).
33
+ *
34
+ * It is also the safe direction. `additive_log` resolves a disagreement by
35
+ * keeping both values silently; applying that to a true one-value fact (a vital
36
+ * status, a date of birth) would leave two contradictory "current" values with
37
+ * no conflict ever surfaced. `single_value_keep_replace` forces the reviewer to
38
+ * look — and because `keep_both_flagged` and `exclude` are offered on EVERY
39
+ * conflict regardless of semantics (L351616-L351617), the fallback never forces
40
+ * a value away.
41
+ *
42
+ * This module answers a FIELD question. Which decision a given review ROW
43
+ * admits (the write gate) also depends on the row's bucket, and is answered by
44
+ * `isOfferedForRow` in `shareFieldReviewPlan.ts`.
45
+ *
46
+ * ## Where the four values come from
47
+ *
48
+ * Not from here. `src/generated/captureConflictSemantics.ts` is generated from
49
+ * the hti-features field_mapping registry by
50
+ * `scripts/gen-capture-conflict-semantics.ts`; never hand-edit it.
51
+ */
52
+
53
+ /** A decision a reviewer can record against one conflict. */
54
+ export type CaptureConflictDecision =
55
+ /** `log_end_date_current` only — theirs becomes current, mine end-dates today. */
56
+ | "theirs_current"
57
+ /** `log_end_date_current` only — mine stays current, theirs joins history. */
58
+ | "mine_current"
59
+ /** Take theirs; mine stays in history by supersession, never deletion. */
60
+ | "replace"
61
+ /** Keep mine; theirs is not adopted. */
62
+ | "keep_mine"
63
+ /**
64
+ * "I don't know yet" — keep BOTH and flag the open conflict on the record.
65
+ *
66
+ * First-class and NON-BLOCKING: the registry doc states it "UNBLOCKS
67
+ * approval", and the prototype offers it on every conflict irrespective of
68
+ * semantics. It is the reason the unauthored fallback cannot destroy
69
+ * information — there is always an escape that decides nothing.
70
+ */
71
+ | "keep_both_flagged"
72
+ /**
73
+ * Decline the offer outright, with a structured reason code.
74
+ *
75
+ * Offered on every conflict row, like `keep_both_flagged` — the prototype
76
+ * renders "Don't bring theirs in…" outside the semantics branch (L351617).
77
+ * NOT in {@link ResolvedCaptureConflictSemantics.choices}: that list is the
78
+ * semantics-driven resolution set, and declining is a different act on a
79
+ * different control carrying a reason code. The row gate `isOfferedForRow`
80
+ * (shareFieldReviewPlan.ts) accounts for it separately.
81
+ */
82
+ | "exclude";
83
+
84
+ /** Why {@link resolvedSemantics} returned the value it did. */
85
+ export type CaptureConflictRulePath =
86
+ /** The registry authors this field explicitly. */
87
+ | "registry_authored"
88
+ /** No upstream ruling; fell back to the prototype's own default branch. */
89
+ | "unauthored_default_keep_replace";
90
+
91
+ export interface ResolvedCaptureConflictSemantics {
92
+ /** The semantics in force — authored or fallen back to. */
93
+ semantics: CaptureConflictSemantics;
94
+ /**
95
+ * Whether the registry actually authored this field.
96
+ *
97
+ * `false` does NOT mean "no conflict semantics apply" — `semantics` still
98
+ * carries the operative value. It means no human upstream has ruled, so a
99
+ * caller that wants to report coverage, or to prompt for authoring, can tell
100
+ * the difference.
101
+ */
102
+ authored: boolean;
103
+ /** Which fact decided. Never omitted, so any resolution can be explained. */
104
+ rulePath: CaptureConflictRulePath;
105
+ /**
106
+ * Whether a disagreement on this field is a CONFLICT a reviewer must resolve.
107
+ *
108
+ * False for `additive_log` ("entries add — never a conflict") and for
109
+ * `no_conflict_derived` ("the value never conflicts because it is derived").
110
+ * Those offers are adopted without blocking the review.
111
+ */
112
+ producesConflict: boolean;
113
+ /**
114
+ * The resolution decisions offered, in the prototype's render order.
115
+ *
116
+ * `keep_both_flagged` is ALWAYS last and ALWAYS present when there is a
117
+ * conflict. Empty when `producesConflict` is false — nothing to decide.
118
+ */
119
+ choices: readonly CaptureConflictDecision[];
120
+ }
121
+
122
+ const KEEP_REPLACE_CHOICES = Object.freeze(["replace", "keep_mine", "keep_both_flagged"] as const);
123
+
124
+ const END_DATE_CHOICES = Object.freeze([
125
+ "theirs_current",
126
+ "mine_current",
127
+ "keep_both_flagged",
128
+ ] as const);
129
+
130
+ const NO_CHOICES = Object.freeze([] as const);
131
+
132
+ /**
133
+ * Resolve the review semantics for one registry field id.
134
+ *
135
+ * Total: every field resolves, because an unauthored one falls back rather
136
+ * than returning nothing. A resolver that could return "unknown" would put the
137
+ * branch in every caller, and the callers would not agree on it.
138
+ */
139
+ export function resolvedSemantics(fieldId: string): ResolvedCaptureConflictSemantics {
140
+ // Own-property check: `BY_FIELD["constructor"]` is truthy on a plain object.
141
+ const authoredValue = Object.prototype.hasOwnProperty.call(
142
+ CAPTURE_CONFLICT_SEMANTICS_BY_FIELD,
143
+ fieldId,
144
+ )
145
+ ? CAPTURE_CONFLICT_SEMANTICS_BY_FIELD[fieldId]
146
+ : undefined;
147
+
148
+ const semantics: CaptureConflictSemantics = authoredValue ?? "single_value_keep_replace";
149
+
150
+ const producesConflict = semantics !== "additive_log" && semantics !== "no_conflict_derived";
151
+
152
+ return {
153
+ semantics,
154
+ authored: authoredValue !== undefined,
155
+ rulePath: authoredValue !== undefined ? "registry_authored" : "unauthored_default_keep_replace",
156
+ producesConflict,
157
+ choices: !producesConflict
158
+ ? NO_CHOICES
159
+ : semantics === "log_end_date_current"
160
+ ? END_DATE_CHOICES
161
+ : KEEP_REPLACE_CHOICES,
162
+ };
163
+ }
164
+
165
+ export {
166
+ CAPTURE_CONFLICT_SEMANTICS,
167
+ CAPTURE_CONFLICT_SEMANTICS_BY_FIELD,
168
+ CAPTURE_CONFLICT_SEMANTICS_SOURCE,
169
+ type CaptureConflictSemantics,
170
+ } from "../generated/captureConflictSemantics.js";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @htilabs/platform-common-models/share-review
3
+ *
4
+ * The pure inbound-CaseShare REVIEW KERNEL (th-hbo9t.2; Thread
5
+ * ADR-THREAD-CASESHARE-INBOUND-REVIEW D-b / D-e), lifted from pave-2.0 and
6
+ * re-keyed by hti-features registry field id (`capture.*`):
7
+ *
8
+ * - the seven review decisions (`REVIEW_DECISIONS`, `isReviewDecision`);
9
+ * - the capture-conflict-semantics resolver (`resolvedSemantics`) over the
10
+ * GENERATED registry table;
11
+ * - the add / conflict planner and its blocking count (`planFieldReview`,
12
+ * `canApproveReview`), and THE row gate (`isOfferedForRow`) the write side
13
+ * calls and the planner resolves conflicts by;
14
+ * - the semantics-routed recommendation (`recommendedDecision`).
15
+ *
16
+ * Pure TypeScript: no mongoose, no I/O, no React. Not re-exported from the
17
+ * package root.
18
+ */
19
+
20
+ export * from "./reviewDecision.js";
21
+ export * from "./captureConflictSemantics.js";
22
+ export * from "./shareFieldReviewPlan.js";
23
+ export * from "./recommendedDecision.js";
@@ -0,0 +1,21 @@
1
+ import type { ReviewDecision } from "./reviewDecision.js";
2
+
3
+ /**
4
+ * Which decision a conflict-row recommendation (or "Accept all") resolves to.
5
+ *
6
+ * Lifted from pave-2.0 packages/composites/src/CaseShareReviewTakeover/
7
+ * RecommendationAssist.tsx @ 312943078 (th-hbo9t.2), where it sat in a React
8
+ * module; it is pure, so it lives in the kernel.
9
+ *
10
+ * Branches on SEMANTICS, exactly as the prototype's handlers do — per-row Apply
11
+ * (canon c2b0b8b0 L351836) and bulk "Accept all" over undecided conflicts
12
+ * (L351827): `log_end_date_current` → `theirs_current`, every other value →
13
+ * `replace`. Not on a stored `recommend.value`: the prototype's seed rows carry
14
+ * that field and its handlers never read it.
15
+ *
16
+ * Either way nothing is destroyed — the held value joins the history (end-dated
17
+ * or superseded).
18
+ */
19
+ export function recommendedDecision(semantics: string): ReviewDecision {
20
+ return semantics === "log_end_date_current" ? "theirs_current" : "replace";
21
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The REVIEW DECISION vocabulary — what a reviewer may record against one
3
+ * offered value in an inbound CaseShare review.
4
+ *
5
+ * Lifted from pave-2.0 packages/domain/src/reviewDecision.ts @ 312943078
6
+ * (th-hbo9t.2); the code is unchanged, the prose is trimmed to this package.
7
+ *
8
+ * One vocabulary over one persisted decision column: {@link FieldOfferDecision}
9
+ * in `shareFieldReviewPlan` is an alias of {@link ReviewDecision}. Which of
10
+ * the seven a given ROW admits is `isOfferedForRow` (the write gate), not this
11
+ * list.
12
+ *
13
+ * add — the offered value JOINS what is there. Recorded on an
14
+ * add row (pre-accepted; also the display-choice and the
15
+ * re-flag reset in the prototype). Never resolves a
16
+ * conflict.
17
+ * theirs_current — `log_end_date_current` only. Theirs becomes current and
18
+ * mine end-dates today.
19
+ * mine_current — `log_end_date_current` only. Mine stays current and
20
+ * theirs joins history.
21
+ * replace — take theirs. Mine stays in history by supersession,
22
+ * never deletion.
23
+ * keep_mine — keep mine; theirs is not adopted.
24
+ * keep_both_flagged — "I don't know yet." Keep BOTH and raise an open-conflict
25
+ * marker on the record. Resolves a conflict without
26
+ * deciding it, which is why an unauthored fallback can
27
+ * never destroy information.
28
+ * exclude — decline the offer outright, WITH a structured reason
29
+ * code. Distinct from `keep_mine`: that one resolves a
30
+ * conflict in favour of the held value, this one refuses
31
+ * the offer and tells the sender why.
32
+ */
33
+ export const REVIEW_DECISIONS = [
34
+ "add",
35
+ "theirs_current",
36
+ "mine_current",
37
+ "replace",
38
+ "keep_mine",
39
+ "keep_both_flagged",
40
+ "exclude",
41
+ ] as const;
42
+
43
+ export type ReviewDecision = (typeof REVIEW_DECISIONS)[number];
44
+
45
+ /**
46
+ * The runtime set, built once.
47
+ *
48
+ * `ReadonlySet<string>` and not `Set<ReviewDecision>`: the caller's input is an
49
+ * arbitrary string off the wire or out of a bare-String column, and typing the
50
+ * set to the union would force every caller to cast the very value it is asking
51
+ * about.
52
+ */
53
+ const REVIEW_DECISION_SET: ReadonlySet<string> = new Set(REVIEW_DECISIONS);
54
+
55
+ /**
56
+ * Whether an arbitrary value is a review decision.
57
+ *
58
+ * An ALLOWLIST, deliberately — never `v != null && v !== "add"` or any other
59
+ * negation. A persisted decision column typically carries no enum, so the
60
+ * values that actually reach this are unconstrained: `""`, `" "`, `0`,
61
+ * `false`, `{}` and any arbitrary string all arrive. Every one of those passes
62
+ * a negation and fails this.
63
+ *
64
+ * That asymmetry is the whole point. A wrong answer here in the permissive
65
+ * direction admits a decision nobody offered onto a survivor record; a wrong
66
+ * answer in the strict direction refuses a legitimate one loudly. Only the
67
+ * second is recoverable.
68
+ */
69
+ export function isReviewDecision(value: unknown): value is ReviewDecision {
70
+ return typeof value === "string" && REVIEW_DECISION_SET.has(value);
71
+ }
@@ -0,0 +1,288 @@
1
+ import {
2
+ type CaptureConflictDecision,
3
+ type CaptureConflictSemantics,
4
+ resolvedSemantics,
5
+ } from "./captureConflictSemantics.js";
6
+ import type { ReviewDecision } from "./reviewDecision.js";
7
+
8
+ /**
9
+ * The FIELD-GRAIN REVIEW PLAN of an inbound CaseShare.
10
+ *
11
+ * Lifted from pave-2.0 packages/domain/src/shareFieldReviewPlan.ts @ 312943078
12
+ * (th-hbo9t.2, Thread ADR-THREAD-CASESHARE-INBOUND-REVIEW D-b), with these changes:
13
+ *
14
+ * - RE-KEYED by registry field id (`fieldId`, e.g. `capture.living_situation`)
15
+ * instead of PAVE's `assertionDomain`.
16
+ * - PAVE's `unverified` bucket (and its tri-state `targetHeld: "unknown"` input)
17
+ * is DROPPED. It is a PAVE-only extra with no canon counterpart: canon has
18
+ * exactly two row kinds, adds and conflicts (`addsOf` / `conflictsOf`, canon
19
+ * c2b0b8b0 L351462-L351463). A caller that cannot establish the held side must
20
+ * not call the planner for that row as if it had.
21
+ * - PAVE's `survivorDeclined` input (its demographics decline lane) is DROPPED.
22
+ * It is a PAVE survivor-record rule, not part of the share-review kernel; a
23
+ * consumer with such a rule applies it before planning.
24
+ * - Decisions are judged PER ROW by one rule, {@link isOfferedForRow}: it is
25
+ * both the write gate and what decides whether a conflict is resolved.
26
+ * - The name display-question row cannot be excluded (canon renders only the
27
+ * two display buttons there), and derived fields get their own rule path.
28
+ *
29
+ * ## Two kinds, and only one of them blocks
30
+ *
31
+ * - An **add** is pre-accepted. The recipient holds nothing that competes, or
32
+ * the field's semantics say entries accumulate or are derived. It does NOT
33
+ * hold up approval.
34
+ * - A **conflict** is blocking until decided. Two values compete and the
35
+ * field's semantics say only one can be current, so a human has to choose.
36
+ *
37
+ * `blockingRemaining` counts undecided conflicts and nothing else — canon's
38
+ * `undecidedCount` is `conflictsOf(s).filter(c => !c.decision).length` (L351464).
39
+ *
40
+ * ## Input contracts
41
+ *
42
+ * - **Only offered fields are planned.** A field the sender did not send (no
43
+ * incoming value) is never an input: there is nothing to add or to decide.
44
+ * Canon builds rows only from the delivered payload (`payload.forEach`,
45
+ * L348703). The planner never synthesizes a row.
46
+ * - **An identical held value is not competing.** When the recipient already
47
+ * holds the same value the sender offers, the caller passes
48
+ * `targetPopulated: false`; the row is a no-op add, never a conflict. (Canon's
49
+ * re-review skips an unchanged value the same way, L348712.)
50
+ *
51
+ * ## NO VALUES CROSS THIS BOUNDARY
52
+ *
53
+ * The planner takes `targetPopulated: boolean`, never the held value and never
54
+ * the incoming one. Bucketing needs to know THAT a value competes, never WHAT
55
+ * it is, so the plan can be computed without a plaintext survivor value in scope.
56
+ */
57
+
58
+ /** One incoming field offer, reduced to what bucketing actually needs. */
59
+ export interface FieldOfferInput {
60
+ /** Stable id of this offer within the share — the handle a decision pulls by. */
61
+ offerId: string;
62
+ /**
63
+ * The hti-features registry field id (`capture.*` and kin). Drives the
64
+ * semantics lookup. Only fields the sender actually offered are planned.
65
+ */
66
+ fieldId: string;
67
+ /**
68
+ * Whether the RECIPIENT already holds a DIFFERENT value for this field.
69
+ *
70
+ * Strictly boolean, and the caller must mean it:
71
+ * - `false` when the recipient looked and holds nothing, or holds exactly the
72
+ * offered value (an identical value does not compete);
73
+ * - `true` only when a different held value competes.
74
+ *
75
+ * It must not be used for "we did not check": that reads as "nothing
76
+ * competes" and pre-accepts an offer that should have been a conflict.
77
+ */
78
+ targetPopulated: boolean;
79
+ /** The recorded decision, when the reviewer has made one. */
80
+ decision?: FieldOfferDecision | null;
81
+ }
82
+
83
+ /**
84
+ * A decision recorded against an offer — an alias of {@link ReviewDecision}, so
85
+ * there is one vocabulary underneath. Which members a ROW admits is
86
+ * {@link isOfferedForRow}.
87
+ */
88
+ export type FieldOfferDecision = ReviewDecision;
89
+
90
+ /**
91
+ * The name display-question's two answers: keep the current display name, or
92
+ * display the incoming one. Canon's `data-rvw-display` buttons (c2b0b8b0
93
+ * L351554-L351555); the click records `display_choice` AND `decision = "add"`
94
+ * (L351893) — both names join the name log either way.
95
+ */
96
+ export const DISPLAY_CHOICES = ["keep", "incoming"] as const;
97
+ export type DisplayChoice = (typeof DISPLAY_CHOICES)[number];
98
+
99
+ /** Why an offer landed in the bucket it did. */
100
+ export type FieldOfferRulePath =
101
+ /** Nothing (different) competes on the recipient side — no question to ask. */
102
+ | "no_held_value"
103
+ /** A value competes, but the field's semantics say entries accumulate. */
104
+ | "additive_never_conflicts"
105
+ /**
106
+ * A value competes, but the field is `no_conflict_derived`. Bucketed as an
107
+ * add (non-blocking, no choices). The prototype is SILENT on whether a
108
+ * derived value offered in a share is adopted as sent or recomputed by the
109
+ * recipient; this kernel decides only that it never blocks review.
110
+ */
111
+ | "derived_never_conflicts"
112
+ /** A value competes and only one can be current. A human must choose. */
113
+ | "conflict_requires_decision";
114
+
115
+ interface PlannedFieldOfferBase {
116
+ offerId: string;
117
+ fieldId: string;
118
+ bucket: "add" | "conflict";
119
+ /**
120
+ * Whether this row is holding up approval RIGHT NOW.
121
+ *
122
+ * Only a conflict without an OFFERED decision ({@link isOfferedForRow}) blocks.
123
+ * An add never does — including one the reviewer has not touched.
124
+ */
125
+ blocking: boolean;
126
+ /** The semantics in force, authored or fallen back to. */
127
+ semantics: CaptureConflictSemantics;
128
+ /** Whether the registry actually authored those semantics. */
129
+ semanticsAuthored: boolean;
130
+ /**
131
+ * The conflict-resolution choices offered (`keep_both_flagged` always last).
132
+ * Empty for an add — there is nothing to resolve. `exclude` is separate; see
133
+ * `canExclude`.
134
+ */
135
+ choices: readonly CaptureConflictDecision[];
136
+ rulePath: FieldOfferRulePath;
137
+ }
138
+
139
+ /**
140
+ * One planned row. `displayQuestion` and `canExclude` are typed together:
141
+ *
142
+ * - A **display-question** row (`capture.name` over a held name) asks only
143
+ * which name displays; it CANNOT be excluded. Canon's add row renders the two
144
+ * display buttons in the `display_question` branch and "Don't add this…" only
145
+ * in the `else if` branch (c2b0b8b0 L351542-L351569); "Two names never
146
+ * conflict; the only question is which one displays" (L346745).
147
+ * - Every other row can be declined with a reason (`exclude`).
148
+ */
149
+ export type PlannedFieldOffer = PlannedFieldOfferBase &
150
+ (
151
+ | {
152
+ /** The record shows ONE name; the reviewer chooses which ({@link DisplayChoice}). */
153
+ displayQuestion: true;
154
+ canExclude: false;
155
+ }
156
+ | {
157
+ displayQuestion: false;
158
+ /** Declining the offer, with a structured reason code, is available. */
159
+ canExclude: true;
160
+ }
161
+ );
162
+
163
+ export interface FieldReviewPlan {
164
+ /** Pre-accepted offers, in input order. */
165
+ adds: PlannedFieldOffer[];
166
+ /** Competing offers, in input order. */
167
+ conflicts: PlannedFieldOffer[];
168
+ /**
169
+ * Undecided conflicts. The number the surface shows and approval gates on.
170
+ *
171
+ * Zero does NOT mean the review is empty — a share of nothing but adds
172
+ * reports zero here and still has rows to render.
173
+ */
174
+ blockingRemaining: number;
175
+ }
176
+
177
+ /**
178
+ * Fields where the record displays ONE representative value while the log
179
+ * holds many, so a second value raises a display question instead of a
180
+ * conflict. Deliberately narrow: the prototype sets `display_question: true` on
181
+ * the name add and on no other row (L346745). A record shows every phone it
182
+ * holds, but ONE name.
183
+ */
184
+ export const DISPLAY_REPRESENTATIVE_FIELDS: ReadonlySet<string> = new Set(["capture.name"]);
185
+
186
+ /**
187
+ * THE row gate: whether `decision` is one this review row admits.
188
+ *
189
+ * The write side MUST call this before persisting a decision, and the planner
190
+ * uses the same rule to decide whether a conflict is resolved — one rule, so a
191
+ * decision the surface would refuse can never clear a blocking row.
192
+ *
193
+ * - **Add row** → `add` (canon writes it on add rows: the seed, the display
194
+ * choice L351893, the re-flag reset L348744), plus `exclude` when the row
195
+ * `canExclude` (not on the name display question).
196
+ * - **Conflict row** → the field's semantics `choices` (the end-date pair OR
197
+ * keep/replace, canon L351609-L351615, plus `keep_both_flagged` L351616) and
198
+ * `exclude` (L351617). Never `add`, and never the OTHER semantics' pair:
199
+ * `replace` does not resolve an end-date conflict, `mine_current` does not
200
+ * resolve a keep/replace one.
201
+ *
202
+ * An allowlist over `unknown`: `""`, `null`, `0`, `{}` and arbitrary strings
203
+ * are refused.
204
+ */
205
+ export function isOfferedForRow(
206
+ row: Pick<PlannedFieldOfferBase, "bucket" | "choices"> & { canExclude: boolean },
207
+ decision: unknown,
208
+ ): decision is FieldOfferDecision {
209
+ if (typeof decision !== "string") return false;
210
+ if (decision === "exclude") return row.canExclude;
211
+ if (row.bucket === "add") return decision === "add";
212
+ return (row.choices as readonly string[]).includes(decision);
213
+ }
214
+
215
+ /**
216
+ * Plan one share's field review.
217
+ *
218
+ * Pure and total: every offer lands in exactly one bucket, so the two arrays
219
+ * always partition the input and no offer can be dropped by falling through.
220
+ */
221
+ export function planFieldReview(offers: readonly FieldOfferInput[]): FieldReviewPlan {
222
+ const adds: PlannedFieldOffer[] = [];
223
+ const conflicts: PlannedFieldOffer[] = [];
224
+
225
+ for (const offer of offers) {
226
+ const semantics = resolvedSemantics(offer.fieldId);
227
+ // Nothing (different) competes ⇒ nothing to decide, whatever the semantics say.
228
+ const competes = offer.targetPopulated === true;
229
+ const isConflict = competes && semantics.producesConflict;
230
+ const bucket = isConflict ? "conflict" : "add";
231
+ const choices = isConflict ? semantics.choices : [];
232
+ const displayQuestion =
233
+ !isConflict && competes && DISPLAY_REPRESENTATIVE_FIELDS.has(offer.fieldId);
234
+
235
+ const rulePath: FieldOfferRulePath = !competes
236
+ ? "no_held_value"
237
+ : isConflict
238
+ ? "conflict_requires_decision"
239
+ : semantics.semantics === "no_conflict_derived"
240
+ ? "derived_never_conflicts"
241
+ : "additive_never_conflicts";
242
+
243
+ const base: PlannedFieldOfferBase = {
244
+ offerId: offer.offerId,
245
+ fieldId: offer.fieldId,
246
+ bucket,
247
+ blocking:
248
+ isConflict && !isOfferedForRow({ bucket, choices, canExclude: true }, offer.decision),
249
+ semantics: semantics.semantics,
250
+ semanticsAuthored: semantics.authored,
251
+ choices,
252
+ rulePath,
253
+ };
254
+ const planned: PlannedFieldOffer = displayQuestion
255
+ ? { ...base, displayQuestion: true, canExclude: false }
256
+ : { ...base, displayQuestion: false, canExclude: true };
257
+
258
+ if (isConflict) conflicts.push(planned);
259
+ else adds.push(planned);
260
+ }
261
+
262
+ return {
263
+ adds,
264
+ conflicts,
265
+ blockingRemaining: conflicts.filter((c) => c.blocking).length,
266
+ };
267
+ }
268
+
269
+ /**
270
+ * Whether the FIELD REVIEW is settled — no conflict is still undecided.
271
+ *
272
+ * ## NOT the whole approve gate
273
+ *
274
+ * This answers ONE condition. Canon's approve path also requires the share to
275
+ * be linked to a case before it looks at any decision (`case_not_linked`, canon
276
+ * c2b0b8b0 L348504); a caller treating this function as THE gate would approve
277
+ * an unlinked share. Named for what it measures so the caller still has to ask
278
+ * the other question.
279
+ *
280
+ * ## Recompute; never trust a stored counter
281
+ *
282
+ * Derive this from the conflicts at the moment of approving; do not read a
283
+ * denormalized per-share counter. An unclaimed share can carry a zero counter
284
+ * while holding undecided conflicts, because its review has not started.
285
+ */
286
+ export function canApproveReview(plan: FieldReviewPlan): boolean {
287
+ return plan.blockingRemaining === 0;
288
+ }