@htilabs/platform-common-models 0.8.22 → 0.8.24

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.
@@ -666,7 +666,9 @@ const SOT_SPECS: readonly SotSpec[] = [
666
666
  { file: "poPetitionBasis.v1.0.0.json", domain: "po_petition_basis", expectedCount: 8 },
667
667
  { file: "poStatus.v1.0.0.json", domain: "po_status", expectedCount: 12 },
668
668
  { file: "poViolationStatus.v1.0.0.json", domain: "po_violation_status", expectedCount: 6 },
669
- { file: "sessionTemplate.v1.0.0.json", domain: "session_template", expectedCount: 23 },
669
+ // 0.8.23: 23 -> 25 — CVC-217 gained cst_pave_inbound_share (217-020) +
670
+ // cst_thread_inbound_share (217-021), the cross-app Inbound Share template pair.
671
+ { file: "sessionTemplate.v1.0.0.json", domain: "session_template", expectedCount: 25 },
670
672
  { file: "serviceDeliveryChannel.v1.0.0.json", domain: "service_delivery_channel", expectedCount: 11 },
671
673
  { file: "whyNots.v1.0.0.json", domain: "why_nots", expectedCount: 32 },
672
674
  // CVC-182 — 249 countries (codes MINTED; upstream Code column is blank) + 1
@@ -702,6 +704,11 @@ const SOT_SPECS: readonly SotSpec[] = [
702
704
  // @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
703
705
  // 3 lifecycle states (@pave/domain ASSERTION_STATUSES) + 4 missingness = 7
704
706
  { file: "assertionStatus.v1.0.0.json", domain: "assertion_status", expectedCount: 7 },
707
+ // 4 correction/retraction reasons (@pave/domain CAR_CORRECTION_REASONS —
708
+ // entered_in_error, duplicate, superseded_externally — plus
709
+ // removed_by_recipient_curation for the CaseShare curation lane) + 4
710
+ // missingness = 8
711
+ { file: "carCorrectionReason.v1.0.0.json", domain: "car_correction_reason", expectedCount: 8 },
705
712
  // 4 actor classes (@pave/domain CREATED_BY_SYSTEMS) + 4 missingness = 8
706
713
  { file: "createdBySystem.v1.0.0.json", domain: "created_by_system", expectedCount: 8 },
707
714
  // 3 entity kinds (@pave/domain SUBJECT_TYPES) + 4 missingness = 7
@@ -0,0 +1,150 @@
1
+ /**
2
+ * CVC `_status`/`_source` provenance parser — unit tests
3
+ *
4
+ * Every fixture string below is copied verbatim from a real, committed SOT
5
+ * file under `src/cvcs/` (not invented) — see the inline citation on each
6
+ * `it()` for the source file, so a reader can `grep` back to the original.
7
+ * Covers every branch `parseCvcStatus` exists to handle: the four maturity
8
+ * states, the structured-object `_status` shape (11 domains), the
9
+ * leading-token fallback (`share_purpose`'s "Synced…" — the one domain whose
10
+ * leading word is none of the three convention keywords), the
11
+ * self-contradictory `core_functions` case the parser is specifically
12
+ * designed to flag, and the `prototype/data/cvcs/*.yaml` source-path
13
+ * extraction.
14
+ */
15
+
16
+ import { describe, it, expect } from "vitest";
17
+
18
+ import { parseCvcStatus } from "../validation/cvcStatus.js";
19
+
20
+ describe("parseCvcStatus", () => {
21
+ it("classifies a DRAFT domain (accommodation_type, src/cvcs/accommodationType.v1.0.0.json)", () => {
22
+ const result = parseCvcStatus({
23
+ _status:
24
+ "DRAFT — TEMPORARY: net-new value-CVC not yet in Notion; provisional 900+ numbering; " +
25
+ "codes from prototype/data/cvcs/core_accommodation_type.yaml; PENDING canonical Notion " +
26
+ "authoring (PAVE Auditability backlog).",
27
+ _source: "prototype/data/cvcs/core_accommodation_type.yaml",
28
+ });
29
+ expect(result.maturity).toBe("draft");
30
+ expect(result.ambiguous).toBe(false);
31
+ expect(result.sourceIsPrototype).toBe(true);
32
+ expect(result.sourcePath).toBe("prototype/data/cvcs/core_accommodation_type.yaml");
33
+ expect(result.rawStatus).toContain("DRAFT — TEMPORARY");
34
+ });
35
+
36
+ it("classifies a PROVISIONAL domain (activity_type, src/cvcs/activityType.v1.0.0.json)", () => {
37
+ const result = parseCvcStatus({
38
+ _status:
39
+ "PROVISIONAL — net-new value-CVC not yet in Notion; provisional 900+ numbering; " +
40
+ "substantive values sourced verbatim from the PAVE @pave/domain enum of the same name " +
41
+ "(D10 source-from-platform-common). PENDING canonical Notion authoring + steward " +
42
+ "ratification of titles/definitions.",
43
+ _source: "pave-2.0/packages/domain/src/enums.ts",
44
+ });
45
+ expect(result.maturity).toBe("provisional");
46
+ expect(result.ambiguous).toBe(false);
47
+ // Cited source is a PAVE TS enum, not a prototype YAML dump.
48
+ expect(result.sourceIsPrototype).toBe(false);
49
+ expect(result.sourcePath).toBeNull();
50
+ });
51
+
52
+ it("classifies a CANONICAL provenance-note domain as its own maturity, not 'draft'/'final' (admin_roles, src/cvcs/adminRoles.v1.0.0.json)", () => {
53
+ const result = parseCvcStatus({
54
+ _status:
55
+ "CANONICAL — imported 0.8.13 from the Notion Final CVC codebook (CVC-134 `core - admin " +
56
+ "roles`, Owner Crysta Price, Status 'Drafted - Needs Review'). Administrative role " +
57
+ "vocabulary for the canonical authorization model (IC-66). DISTINCT from CVC-135 " +
58
+ "`user_roles` (the operational/practitioner role axis) — a person may hold both.",
59
+ _source:
60
+ "htilabstech/prototype@a596eb9 Final CVCs/System Roles, Permissions, & Account " +
61
+ "Management (IC-66)/core - admin roles (CVC-134)",
62
+ });
63
+ // A "CANONICAL" leading marker is a provenance note on an ALREADY-ratified
64
+ // file — kept as its own state, distinct from "final" (the absent-field
65
+ // legacy case), so a caller can tell "explicitly marked ratified" apart
66
+ // from "predates the convention entirely".
67
+ expect(result.maturity).toBe("canonical");
68
+ expect(result.ambiguous).toBe(false);
69
+ expect(result.sourceIsPrototype).toBe(false);
70
+ });
71
+
72
+ it("classifies an absent `_status` as 'final' — legacy/unmarked, predates the convention (administering_jurisdiction, src/cvcs/administeringJurisdiction.v1.0.0.json)", () => {
73
+ const result = parseCvcStatus({});
74
+ expect(result.maturity).toBe("final");
75
+ expect(result.rawStatus).toBeNull();
76
+ expect(result.ambiguous).toBe(false);
77
+ expect(result.sourceIsPrototype).toBe(false);
78
+ expect(result.sourcePath).toBeNull();
79
+ });
80
+
81
+ it("flags the self-contradictory core_functions case as ambiguous, generically — not a special case for this one domain (src/cvcs/coreFunctions.v1.0.0.json)", () => {
82
+ const result = parseCvcStatus({
83
+ _status:
84
+ "DRAFTED — NEEDS REVIEW: canonical Notion CVC-133 (core - functions), verified v1.0, " +
85
+ "ported verbatim from the Notion codebook. Canonical numbering (133), NOT provisional. " +
86
+ "Per-entry lifecycle Status (v1 / future / not-started) is carried in each definition.",
87
+ _source: "Notion CVC-133 core - functions (collection://3211ef14-abcd-8024-867d-000be4b35a79)",
88
+ });
89
+ // Leading token "DRAFTED" still drives the primary classification…
90
+ expect(result.maturity).toBe("draft");
91
+ // …but the string also asserts "NOT provisional" later on, which the
92
+ // parser catches generically (scans the whole string for a negated
93
+ // maturity keyword) rather than via a domain-name special case, so any
94
+ // future domain authored in this same self-contradictory shape is also
95
+ // caught automatically.
96
+ expect(result.ambiguous).toBe(true);
97
+ });
98
+
99
+ it("falls back to a whole-string keyword scan when the leading token is none of the three convention words (share_purpose, src/cvcs/sharePurpose.v1.0.0.json)", () => {
100
+ const result = parseCvcStatus({
101
+ _status:
102
+ "Synced verbatim from canonical CVC-84 (renamed `core-sharing_purpose` 2026-08-19). " +
103
+ "8 core rows from `core_share_purpose.yaml` + 4 LEADS-wing rows from " +
104
+ "`core_share_purpose_extensions_leads.yaml`… The wing rows were RATIFIED 2026-07-03 " +
105
+ "and live-synced 2026-08-19 (no longer proposal-only).",
106
+ _source: "htilabstech/prototype data/cvcs/core_share_purpose.yaml + core_share_purpose_extensions_leads.yaml",
107
+ });
108
+ // Leading token is "Synced" — none of draft/provisional/canonical. The
109
+ // body contains exactly one keyword family ("canonical"), so the parser
110
+ // accepts it unambiguously rather than defaulting to "final" (which per
111
+ // the module rule is reserved for an ABSENT `_status`, not merely an
112
+ // unrecognized leading word on a present one).
113
+ expect(result.maturity).toBe("canonical");
114
+ expect(result.ambiguous).toBe(false);
115
+ });
116
+
117
+ it("reads the structured-object `_status` shape via its `vocabStatus` field, not the whole object (citizenship, src/cvcs/citizenship.v1.0.0.json)", () => {
118
+ const result = parseCvcStatus({
119
+ _status: {
120
+ vocabStatus: "provisional-pending-notion-ratification",
121
+ authoredBy: "platform-common 0.8.13",
122
+ evidence:
123
+ "prototype@a596eb9 'Final CVCs/Socioeconomic Demographics (IC-69)/Nationality & " +
124
+ "Citizenship (IC-60)/core - citizenship — codebook 2.csv' (252 rows) + " +
125
+ "CVC_INDEX.md:25 (core - citizenship = CVC-182, status 'Not started').",
126
+ },
127
+ });
128
+ expect(result.maturity).toBe("provisional");
129
+ expect(result.rawStatus).toBe("provisional-pending-notion-ratification");
130
+ expect(result.ambiguous).toBe(false);
131
+ });
132
+
133
+ it("reads the structured-object `_status` shape's 'canonical' vocabStatus (person_relationships, src/cvcs/personRelationships.v1.0.0.json)", () => {
134
+ const result = parseCvcStatus({
135
+ _status: { vocabStatus: "canonical", authoredBy: "platform-common 0.8.14" },
136
+ });
137
+ expect(result.maturity).toBe("canonical");
138
+ expect(result.rawStatus).toBe("canonical");
139
+ expect(result.ambiguous).toBe(false);
140
+ });
141
+
142
+ it("ignores a non-string `_source` and a `_source` with no prototype YAML citation", () => {
143
+ const noSource = parseCvcStatus({ _status: "DRAFT — x" });
144
+ expect(noSource.sourceIsPrototype).toBe(false);
145
+ expect(noSource.sourcePath).toBeNull();
146
+
147
+ const nonStringSource = parseCvcStatus({ _status: "DRAFT — x", _source: 42 });
148
+ expect(nonStringSource.sourceIsPrototype).toBe(false);
149
+ });
150
+ });
@@ -0,0 +1,89 @@
1
+ {
2
+ "domain": "car_correction_reason",
3
+ "name": "CAR Correction Reason",
4
+ "version": "1.0.0",
5
+ "_status": "DRAFT — TEMPORARY: net-new value-CVC not yet in Notion; provisional 900+ numbering (992). Non-clinical bookkeeping/provenance vocabulary — the coded KIND of a CAR (Contextual Assertion Record) correction or retraction, engineer-direct-authored per the PAVE CVC-authoring governance steer (structural, provisional/ratify-later; FYI to Crysta, NOT Crysta-gated). The first three tokens are sourced verbatim from PAVE `@pave/domain` CAR_CORRECTION_REASONS / RETRACTION_TYPES (packages/domain/src/carGovernance.ts), themselves hoisted from packages/db/src/services/assertionRetraction.ts's documented `retractionType` set; publishing them here retires that PAVE-local const in favour of the SOT it always wanted (carGovernance.ts §'Where these labels are DERIVED' notes 'the day a CVC publishes these three the swap is one deriveLabels call'). The fourth, removed_by_recipient_curation, is added for the PAVE CaseShare received-content curation lane (bead pv-p6share-curation-retract-reason-vocab, 2026-09-18). CASING: lower_snake per the CVC key regex. PENDING canonical Notion authoring + steward ratification.",
6
+ "_source": "pave-2.0/packages/domain/src/carGovernance.ts CAR_CORRECTION_REASONS; pave-2.0/packages/db/src/services/assertionRetraction.ts RetractAssertionInput.retractionType; removed_by_recipient_curation net-new for the received-content curation lane (pv-p6share-curation-retract-reason-vocab)",
7
+ "levels": {
8
+ "0": "Unknown or Missing",
9
+ "1": "CAR correction / retraction reason (single-select per correction event)"
10
+ },
11
+ "entries": [
12
+ {
13
+ "code": "992-000-000-000-000-000-000",
14
+ "key": "missingness_root",
15
+ "title": "Unknown, Redacted, or Missing",
16
+ "selectable": false,
17
+ "parentCode": null,
18
+ "childCodes": [
19
+ "992-000-000-000-000-000-001",
20
+ "992-000-000-000-000-000-002",
21
+ "992-000-000-000-000-000-003"
22
+ ],
23
+ "definition": "Root group for values indicating absent, withheld, or uncollected data. Variant: 3-value (unknown, anonymous, data_not_collected). No prefer_not_to_answer — workspace standard ANON semantic rolls 'declined to answer' into the anonymous sentinel. A correction reason is always explicitly chosen in practice; the quadruplet is present per SOT convention, not because a correction is expected to be missing."
24
+ },
25
+ {
26
+ "code": "992-000-000-000-000-000-001",
27
+ "key": "unknown",
28
+ "title": "Unknown",
29
+ "selectable": true,
30
+ "parentCode": "992-000-000-000-000-000-000",
31
+ "childCodes": [],
32
+ "definition": "Value is unknown at time of entry."
33
+ },
34
+ {
35
+ "code": "992-000-000-000-000-000-002",
36
+ "key": "anonymous",
37
+ "title": "Anonymous / declined to answer",
38
+ "selectable": true,
39
+ "parentCode": "992-000-000-000-000-000-000",
40
+ "childCodes": [],
41
+ "definition": "Value is intentionally withheld or redacted. Combines declined-to-answer and redacted/anonymous semantics under the workspace standard ANON sentinel."
42
+ },
43
+ {
44
+ "code": "992-000-000-000-000-000-003",
45
+ "key": "data_not_collected",
46
+ "title": "Data not collected",
47
+ "selectable": true,
48
+ "parentCode": "992-000-000-000-000-000-000",
49
+ "childCodes": [],
50
+ "definition": "No attempt was made to collect the value."
51
+ },
52
+ {
53
+ "code": "992-001-000-000-000-000-000",
54
+ "key": "entered_in_error",
55
+ "title": "Entered in error",
56
+ "selectable": true,
57
+ "parentCode": null,
58
+ "childCodes": [],
59
+ "definition": "The assertion should never have been recorded — it was captured by mistake (wrong subject, wrong field, an advocate mis-click, or a claim the conversation did not actually support). The row is RETRACTED, not hard-deleted: a retraction retains the row it retracts so the log of record stays forensic. The canonical 'this is not true and never was' correction."
60
+ },
61
+ {
62
+ "code": "992-002-000-000-000-000-000",
63
+ "key": "duplicate",
64
+ "title": "Duplicate of another assertion",
65
+ "selectable": true,
66
+ "parentCode": null,
67
+ "childCodes": [],
68
+ "definition": "The same claim was asserted twice in the same spine partition (e.g. captured from two surfaces, or re-emitted by an ingest path that did not de-duplicate). The duplicate copy is retracted; the canonical copy remains active. Distinct from entered_in_error: the claim IS true, it is merely recorded more than once."
69
+ },
70
+ {
71
+ "code": "992-003-000-000-000-000-000",
72
+ "key": "superseded_externally",
73
+ "title": "Superseded externally",
74
+ "selectable": true,
75
+ "parentCode": null,
76
+ "childCodes": [],
77
+ "definition": "The assertion is retired because a truer or more current value arrived from OUTSIDE the ordinary in-partition supersession chain (e.g. a corrected value from another system or a later disclosure that a normal supersede row could not express). Use when the successor is not itself a spine row that carries `supersedes_assertion_id`; where an in-partition successor exists, status 'superseded' with `supersedes_assertion_id` is the right shape instead."
78
+ },
79
+ {
80
+ "code": "992-004-000-000-000-000-000",
81
+ "key": "removed_by_recipient_curation",
82
+ "title": "Removed by recipient curation",
83
+ "selectable": true,
84
+ "parentCode": null,
85
+ "childCodes": [],
86
+ "definition": "Recipient-side curation removal of a received (re-emitted) assertion; added for PAVE CaseShare received-content curation, 2026-09-18. A recipient agency curates a cleanly-attributed foreign re-emitted CAR (indicator / victimization / involvement) out of their own record — the claim is not asserted as false, it is simply not one this recipient chooses to carry. The row is RETRACTED with this coded, honest reason rather than silently dropped, so the received-then-removed sequence stays on the log of record and the origin's assertion is untouched. Distinct from entered_in_error (a mistaken capture) and from duplicate (a redundant copy): the assertion was validly received and validly removed by the receiving side's curation decision."
87
+ }
88
+ ]
89
+ }
package/src/cvcs/index.ts CHANGED
@@ -196,6 +196,7 @@ import suggestionSourceSot from "./suggestionSource.v1.0.0.json" with { type: "j
196
196
  // GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE @pave/domain
197
197
  // verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish).
198
198
  import assertionStatusSot from "./assertionStatus.v1.0.0.json" with { type: "json" };
199
+ import carCorrectionReasonSot from "./carCorrectionReason.v1.0.0.json" with { type: "json" };
199
200
  import createdBySystemSot from "./createdBySystem.v1.0.0.json" with { type: "json" };
200
201
  import subjectTypeSot from "./subjectType.v1.0.0.json" with { type: "json" };
201
202
  import minorAdultStatusSot from "./minorAdultStatus.v1.0.0.json" with { type: "json" };
@@ -389,6 +390,7 @@ export {
389
390
  sessionNoteVisibilitySot,
390
391
  suggestionSourceSot,
391
392
  assertionStatusSot,
393
+ carCorrectionReasonSot,
392
394
  createdBySystemSot,
393
395
  subjectTypeSot,
394
396
  minorAdultStatusSot,
@@ -256,6 +256,28 @@
256
256
  "childCodes": [],
257
257
  "definition": "Catch-all session template for non-field, non-hotline interactions conducted virtually (video or other virtual meeting formats) when no more specific template applies.",
258
258
  "canonicalCode": "CST-UNK-OTHER_VIRTUAL"
259
+ },
260
+ {
261
+ "code": "217-020-000-000-000-000-000",
262
+ "key": "cst_pave_inbound_share",
263
+ "title": "Inbound Share",
264
+ "selectable": true,
265
+ "parentCode": null,
266
+ "childCodes": [],
267
+ "definition": "Review a case another agency shared with your team — claim, set up the record, decide field by field.",
268
+ "canonicalCode": "CST-PAVE-INBOUND_SHARE",
269
+ "application": "PAVE"
270
+ },
271
+ {
272
+ "code": "217-021-000-000-000-000-000",
273
+ "key": "cst_thread_inbound_share",
274
+ "title": "Inbound Share",
275
+ "selectable": true,
276
+ "parentCode": null,
277
+ "childCodes": [],
278
+ "definition": "Review a case another agency shared with your team — claim, set up the record, decide field by field.",
279
+ "canonicalCode": "CST-THREAD-INBOUND_SHARE",
280
+ "application": "Thread"
259
281
  }
260
282
  ]
261
283
  }
@@ -4797,7 +4797,7 @@ export type PoViolationStatusKey = keyof typeof PoViolationStatusKeys;
4797
4797
  /**
4798
4798
  * Key → positional code map for the `session_template` CVC domain (CVC-217). Canonical session templates across PAVE / Thread / LEADS; distinct from CVC-216 `session_state`.
4799
4799
  *
4800
- * Domain: `session_template` · Version: 1.0.0 · Entries: 23
4800
+ * Domain: `session_template` · Version: 1.0.0 · Entries: 25
4801
4801
  */
4802
4802
  export const SessionTemplateKeys = {
4803
4803
  missingness_root: "217-000-000-000-000-000-000",
@@ -4823,6 +4823,8 @@ export const SessionTemplateKeys = {
4823
4823
  cst_leads_new_case: "217-017-000-000-000-000-000",
4824
4824
  cst_leads_new_lead_tip: "217-018-000-000-000-000-000",
4825
4825
  cst_unk_other_virtual: "217-019-000-000-000-000-000",
4826
+ cst_pave_inbound_share: "217-020-000-000-000-000-000",
4827
+ cst_thread_inbound_share: "217-021-000-000-000-000-000",
4826
4828
  } as const;
4827
4829
 
4828
4830
  export type SessionTemplateKey = keyof typeof SessionTemplateKeys;
@@ -5519,6 +5521,24 @@ export const AssertionStatusKeys = {
5519
5521
 
5520
5522
  export type AssertionStatusKey = keyof typeof AssertionStatusKeys;
5521
5523
 
5524
+ /**
5525
+ * Key → positional code map for the `car_correction_reason` CVC domain (provisional CVC-992; the coded KIND of a CAR correction/retraction — entered_in_error / duplicate / superseded_externally, sourced verbatim from PAVE @pave/domain CAR_CORRECTION_REASONS, plus removed_by_recipient_curation for the CaseShare received-content curation lane, bead pv-p6share-curation-retract-reason-vocab; PROVISIONAL, pending Notion ratification).
5526
+ *
5527
+ * Domain: `car_correction_reason` · Version: 1.0.0 · Entries: 8
5528
+ */
5529
+ export const CarCorrectionReasonKeys = {
5530
+ missingness_root: "992-000-000-000-000-000-000",
5531
+ unknown: "992-000-000-000-000-000-001",
5532
+ anonymous: "992-000-000-000-000-000-002",
5533
+ data_not_collected: "992-000-000-000-000-000-003",
5534
+ entered_in_error: "992-001-000-000-000-000-000",
5535
+ duplicate: "992-002-000-000-000-000-000",
5536
+ superseded_externally: "992-003-000-000-000-000-000",
5537
+ removed_by_recipient_curation: "992-004-000-000-000-000-000",
5538
+ } as const;
5539
+
5540
+ export type CarCorrectionReasonKey = keyof typeof CarCorrectionReasonKeys;
5541
+
5522
5542
  /**
5523
5543
  * Key → positional code map for the `created_by_system` CVC domain (GDR §10.1 `core - created_by_system`; creating actor class; PROVISIONAL, pending Notion ratification).
5524
5544
  *
@@ -0,0 +1,209 @@
1
+ /**
2
+ * @htilabs/platform-common-models — CVC `_status`/`_source` provenance parser
3
+ *
4
+ * Problem this solves: `_status` on a SOT envelope (`src/cvcs/*.json`) is
5
+ * unvalidated free text (115 of 179 domains carry it; the rest predate the
6
+ * convention). A consumer that wants to know "is this actually a draft?" has
7
+ * had to eyeball a string like
8
+ *
9
+ * "DRAFT — TEMPORARY: net-new value-CVC not yet in Notion; provisional
10
+ * 900+ numbering; codes from prototype/data/cvcs/core_accommodation_type
11
+ * .yaml; PENDING canonical Notion authoring (PAVE Auditability backlog)."
12
+ *
13
+ * and get it right past two real traps observed across the current
14
+ * population:
15
+ * - A leading `"CANONICAL — …"` marker is a PROVENANCE note on an
16
+ * ALREADY-ratified file, not a maturity warning — it must not be lumped
17
+ * in with `"DRAFT"`/`"PROVISIONAL"`.
18
+ * - `core_functions` is self-contradictory: it leads
19
+ * `"DRAFTED — NEEDS REVIEW"` but the same string continues
20
+ * `"…Canonical numbering (133), NOT provisional."` A naive
21
+ * leading-word reader silently picks one side; this parser flags it.
22
+ *
23
+ * This module is a pure, additive, standalone export. It does NOT touch
24
+ * `CvcEnvelopeSchema` (`./cvc.ts`) — `_status`/`_source` are intentionally
25
+ * outside that Zod schema (see its module header), and adding them there
26
+ * would risk changing parse behavior for every existing consumer. Callers
27
+ * pass the RAW parsed JSON object (before or instead of
28
+ * `CvcEnvelopeSchema.parse()`), not the Zod-inferred `CvcEnvelope`.
29
+ *
30
+ * Classification rule (leading token of `_status`, case-insensitive):
31
+ * - contains "draft" → `maturity: "draft"`
32
+ * - contains "provisional" → `maturity: "provisional"`
33
+ * - contains "canonical" → `maturity: "canonical"` (a provenance note on
34
+ * an already-ratified file, NOT a maturity flag — kept distinct from
35
+ * `"final"` below so a caller can tell "explicitly marked ratified"
36
+ * apart from "predates the convention entirely")
37
+ * - `_status` absent entirely → `maturity: "final"` (legacy/unmarked)
38
+ *
39
+ * One real domain (`share_purpose` — "Synced verbatim from canonical
40
+ * CVC-84…") has a present `_status` whose LEADING token ("Synced") is none
41
+ * of the three convention words. Rather than mis-file it as `"final"` (which
42
+ * per the rule above is reserved for an ABSENT field) this parser falls back
43
+ * to scanning the full string for a single unambiguous keyword family before
44
+ * giving up — see `detectMaturity` below.
45
+ */
46
+
47
+ // ─── Public shape ───────────────────────────────────────────────────────────
48
+
49
+ /**
50
+ * The subset of a raw (pre-validation) SOT envelope this parser reads.
51
+ * Deliberately NOT the Zod-inferred `CvcEnvelope` from `./cvc.ts` — that type
52
+ * is the *parsed* shape, which does not declare `_status`/`_source` at all
53
+ * (they live outside the locked envelope schema on purpose). Pass the raw
54
+ * `JSON.parse()` result of a `src/cvcs/*.json` file here.
55
+ */
56
+ export interface RawCvcEnvelopeProvenance {
57
+ _status?: unknown;
58
+ _source?: unknown;
59
+ }
60
+
61
+ /** The four observed maturity states. See module header for the rule. */
62
+ export type CvcMaturity = "draft" | "provisional" | "canonical" | "final";
63
+
64
+ export interface CvcStatusInfo {
65
+ /** One of the four states; see module header for the classification rule. */
66
+ maturity: CvcMaturity;
67
+ /**
68
+ * The text this parser classified. For a string `_status` this is that
69
+ * string verbatim. For the 11 domains authored with a structured
70
+ * `_status` object (`{ vocabStatus, authoredBy, evidence, … }` — e.g.
71
+ * `citizenship`, `core_functions`'s sibling `countries`), this is
72
+ * `_status.vocabStatus` — the field those envelopes use for exactly this
73
+ * purpose — not the whole object. `null` iff `_status` is absent.
74
+ */
75
+ rawStatus: string | null;
76
+ /** True iff `_source` cites a `prototype/data/cvcs/*.yaml` path. */
77
+ sourceIsPrototype: boolean;
78
+ /** The cited `prototype/data/cvcs/*.yaml` path, or `null` if none. */
79
+ sourcePath: string | null;
80
+ /**
81
+ * True when the classification is a judgment call rather than a clean
82
+ * read: either the leading token disagrees with a later
83
+ * "NOT draft"/"NOT provisional"/"NOT canonical" qualifier in the same
84
+ * string (the `core_functions` shape — generic, not special-cased, so any
85
+ * future domain authored in the same self-contradictory shape is also
86
+ * caught), or the string carries more than one maturity keyword family
87
+ * with no leading token to arbitrate between them.
88
+ */
89
+ ambiguous: boolean;
90
+ }
91
+
92
+ // ─── Implementation ─────────────────────────────────────────────────────────
93
+
94
+ const MATURITY_KEYWORDS: ReadonlyArray<{
95
+ keyword: string;
96
+ maturity: Exclude<CvcMaturity, "final">;
97
+ }> = [
98
+ { keyword: "draft", maturity: "draft" },
99
+ { keyword: "provisional", maturity: "provisional" },
100
+ { keyword: "canonical", maturity: "canonical" },
101
+ ];
102
+
103
+ /** Matches a `prototype/data/cvcs/<file>.yaml` citation anywhere in `_source`. */
104
+ const PROTOTYPE_SOURCE_RE = /(prototype\/data\/cvcs\/[A-Za-z0-9_.-]+\.yaml)/;
105
+
106
+ /**
107
+ * A maturity keyword explicitly negated ("NOT provisional.") anywhere in the
108
+ * string — the self-contradiction signal. Deliberately scans the WHOLE
109
+ * string (not just past the leading token): the qualifier that disagrees
110
+ * with the leading word is, by construction, never the leading word itself.
111
+ */
112
+ const NEGATED_MATURITY_RE = /\bnot\s+(draft|provisional|canonical)\b/i;
113
+
114
+ /**
115
+ * Extract the text this parser classifies against, from either `_status`
116
+ * shape observed in the current SOT population:
117
+ * - `string` (104 of 115 status-bearing domains) → the string itself.
118
+ * - `{ vocabStatus: string, … }` (11 domains — a richer, hand-authored
119
+ * provenance record) → `vocabStatus`, the field those envelopes use for
120
+ * exactly this classification (values seen: `"canonical"` and
121
+ * `"provisional-pending-notion-ratification"`).
122
+ * - Anything else present but shapeless (unseen in the current 179-domain
123
+ * population) → `JSON.stringify` as a last resort, so a future oddity
124
+ * still gets a best-effort classification instead of silently vanishing.
125
+ * - Absent → `null`.
126
+ */
127
+ function extractClassificationText(status: unknown): string | null {
128
+ if (typeof status === "string") return status;
129
+ if (status !== null && typeof status === "object") {
130
+ const vocabStatus = (status as Record<string, unknown>).vocabStatus;
131
+ if (typeof vocabStatus === "string") return vocabStatus;
132
+ return JSON.stringify(status);
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /** The first "word" of a status string, lowercased, for the leading-token rule. */
138
+ function leadingToken(text: string): string {
139
+ return (text.trim().split(/[\s—–:-]+/, 1)[0] ?? "").toLowerCase();
140
+ }
141
+
142
+ /**
143
+ * Classify a present, non-null `_status` text into a maturity + ambiguity
144
+ * flag. Isolated from {@link parseCvcStatus} so the fallback path (the
145
+ * `share_purpose` shape) and the negation check are each unit-testable in
146
+ * isolation.
147
+ */
148
+ function detectMaturity(text: string): { maturity: Exclude<CvcMaturity, "final">; ambiguous: boolean } {
149
+ const lead = leadingToken(text);
150
+ const leadMatch = MATURITY_KEYWORDS.find(({ keyword }) => lead.includes(keyword));
151
+
152
+ let maturity: Exclude<CvcMaturity, "final">;
153
+ if (leadMatch) {
154
+ maturity = leadMatch.maturity;
155
+ } else {
156
+ // The leading token is none of the three convention words. Observed once
157
+ // in the current population: `share_purpose`'s
158
+ // "Synced verbatim from canonical CVC-84…" — "Synced" leads, but the
159
+ // string is unambiguously describing an already-ratified vocabulary.
160
+ // Fall back to scanning the WHOLE string for maturity keyword families
161
+ // rather than defaulting to "final": the field IS present, and "final"
162
+ // per the module-header rule is reserved for an ABSENT `_status`.
163
+ const foundFamilies = MATURITY_KEYWORDS.filter(({ keyword }) =>
164
+ new RegExp(`\\b${keyword}\\w*\\b`, "i").test(text),
165
+ );
166
+ const distinctFamilies = new Set(foundFamilies.map((f) => f.maturity));
167
+ if (distinctFamilies.size === 1) {
168
+ // Single unambiguous family found in the body — safe to accept.
169
+ maturity = foundFamilies[0].maturity;
170
+ return { maturity, ambiguous: false };
171
+ }
172
+ if (distinctFamilies.size > 1) {
173
+ // Multiple families present with no leading token to arbitrate.
174
+ // Report the first-occurring family as a best-effort primary and let
175
+ // the caller see `ambiguous: true` — never silently pick a winner.
176
+ maturity = foundFamilies[0].maturity;
177
+ return { maturity, ambiguous: true };
178
+ }
179
+ // No maturity keyword anywhere in a present `_status` string. Unseen in
180
+ // the current 179-domain population; treat conservatively as
181
+ // "provisional" (the least-committal non-final bucket) rather than
182
+ // silently promoting an unrecognized status to a settled one, and flag
183
+ // it for human attention.
184
+ return { maturity: "provisional", ambiguous: true };
185
+ }
186
+
187
+ return { maturity, ambiguous: NEGATED_MATURITY_RE.test(text) };
188
+ }
189
+
190
+ /**
191
+ * Parse a SOT envelope's `_status`/`_source` provenance fields into a
192
+ * structured, typed result. Pure function — no filesystem access, no
193
+ * dependency on `CvcEnvelopeSchema`. See module header for the full rule and
194
+ * the two known traps it exists to catch.
195
+ */
196
+ export function parseCvcStatus(envelope: RawCvcEnvelopeProvenance): CvcStatusInfo {
197
+ const source = typeof envelope._source === "string" ? envelope._source : null;
198
+ const protoMatch = source?.match(PROTOTYPE_SOURCE_RE) ?? null;
199
+ const sourceIsPrototype = protoMatch !== null;
200
+ const sourcePath = protoMatch?.[1] ?? null;
201
+
202
+ const text = extractClassificationText(envelope._status);
203
+ if (text === null) {
204
+ return { maturity: "final", rawStatus: null, sourceIsPrototype, sourcePath, ambiguous: false };
205
+ }
206
+
207
+ const { maturity, ambiguous } = detectMaturity(text);
208
+ return { maturity, rawStatus: text, sourceIsPrototype, sourcePath, ambiguous };
209
+ }
@@ -13,3 +13,4 @@
13
13
  */
14
14
 
15
15
  export * from "./cvc.js";
16
+ export * from "./cvcStatus.js";