@disclosureos/records 2.0.0-beta.1 → 2.0.0-beta.2

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.
@@ -126,9 +126,9 @@ function parsePrimitiveRecord(input) {
126
126
  unchecked.add(ref2);
127
127
  continue;
128
128
  }
129
- const target2 = assertions.get(ref2.slice("assertion:".length));
130
- if (!target2) issues.push({ code: "REF.LOCAL_RESOLUTION", stage: "semantic", pointer: `/${field}/sourceRefs/${index}`, message: "Local assertion does not exist." });
131
- else if (target2.field !== field) issues.push({ code: "REF.FIELD_MISMATCH", stage: "semantic", pointer: `/${field}/sourceRefs/${index}`, message: "Assertion concerns a different field." });
129
+ const target3 = assertions.get(ref2.slice("assertion:".length));
130
+ if (!target3) issues.push({ code: "REF.LOCAL_RESOLUTION", stage: "semantic", pointer: `/${field}/sourceRefs/${index}`, message: "Local assertion does not exist." });
131
+ else if (target3.field !== field) issues.push({ code: "REF.FIELD_MISMATCH", stage: "semantic", pointer: `/${field}/sourceRefs/${index}`, message: "Assertion concerns a different field." });
132
132
  }
133
133
  const selection = value.selection;
134
134
  if (!selection) continue;
@@ -141,9 +141,9 @@ function parsePrimitiveRecord(input) {
141
141
  for (const [index, ref2] of selection.consideredAssertionRefs.entries()) {
142
142
  if (refs.has(ref2)) issues.push({ code: "REF.UNIQUE_ID", stage: "semantic", pointer: `${path}/consideredAssertionRefs/${index}`, message: "Considered assertion is repeated." });
143
143
  refs.add(ref2);
144
- const target2 = assertions.get(ref2.slice("assertion:".length));
145
- if (!target2) issues.push({ code: "REF.LOCAL_RESOLUTION", stage: "semantic", pointer: `${path}/consideredAssertionRefs/${index}`, message: "Considered assertion does not exist." });
146
- else if (target2.field !== field) issues.push({ code: "REF.FIELD_MISMATCH", stage: "semantic", pointer: `${path}/consideredAssertionRefs/${index}`, message: "Considered assertion concerns a different field." });
144
+ const target3 = assertions.get(ref2.slice("assertion:".length));
145
+ if (!target3) issues.push({ code: "REF.LOCAL_RESOLUTION", stage: "semantic", pointer: `${path}/consideredAssertionRefs/${index}`, message: "Considered assertion does not exist." });
146
+ else if (target3.field !== field) issues.push({ code: "REF.FIELD_MISMATCH", stage: "semantic", pointer: `${path}/consideredAssertionRefs/${index}`, message: "Considered assertion concerns a different field." });
147
147
  }
148
148
  const selected = assertions.get(selection.assertionRef.slice("assertion:".length));
149
149
  if (!selected) issues.push({ code: "REF.LOCAL_RESOLUTION", stage: "semantic", pointer: `${path}/assertionRef`, message: "Selected assertion does not exist." });
@@ -383,9 +383,9 @@ function parseExperimentalObservation(input) {
383
383
  resolve(value.assertionRef, `${selectionPath}/assertionRef`, owner);
384
384
  if (!value.consideredAssertionRefs.includes(value.assertionRef)) problem("SELECTION.INPUTS", `${selectionPath}/assertionRef`, "Selected assertion must be among considered inputs.");
385
385
  if (!refs.includes(value.assertionRef)) problem("SELECTION.SOURCE_REF", `${path}/sourceRefs`, "Field must cite the selected assertion.");
386
- const target2 = assertions.get(key(value.assertionRef));
387
- if (target2 && !matchesField(value.assertionRef, field, measurementId)) problem("REF.FIELD_MISMATCH", `${selectionPath}/assertionRef`, "Selected assertion concerns a different field or measurement.");
388
- else if (target2 && JSON.stringify(target2.value) !== JSON.stringify(selectedValue)) problem("SELECTION.VALUE_MISMATCH", `${path}/value`, "Selection must copy the cited assertion value exactly; processing is declared separately.");
386
+ const target3 = assertions.get(key(value.assertionRef));
387
+ if (target3 && !matchesField(value.assertionRef, field, measurementId)) problem("REF.FIELD_MISMATCH", `${selectionPath}/assertionRef`, "Selected assertion concerns a different field or measurement.");
388
+ else if (target3 && JSON.stringify(target3.value) !== JSON.stringify(selectedValue)) problem("SELECTION.VALUE_MISMATCH", `${path}/value`, "Selection must copy the cited assertion value exactly; processing is declared separately.");
389
389
  }
390
390
  instant(data.createdAt, "/createdAt");
391
391
  instant(data.updatedAt, "/updatedAt");
@@ -457,10 +457,10 @@ function parseExperimentalObservation(input) {
457
457
  }
458
458
  if (queue.length !== graph.size) problem("PROCESS.CYCLE", "/processing", "Local processing/provenance dependencies contain a cycle.");
459
459
  const checks = { structural: "passed", semantic: issues.length ? "failed" : "passed", profile: "not_checked", external: "not_checked" };
460
- const uncheckedRefs = [...sources.keys()].map((id5) => `source:${id5}`).concat(
461
- [...products.keys()].map((id5) => `product:${id5}`),
462
- [...methods.keys()].map((id5) => `method:${id5}`),
463
- [...frames.keys()].map((id5) => `frame:${id5}`)
460
+ const uncheckedRefs = [...sources.keys()].map((id7) => `source:${id7}`).concat(
461
+ [...products.keys()].map((id7) => `product:${id7}`),
462
+ [...methods.keys()].map((id7) => `method:${id7}`),
463
+ [...frames.keys()].map((id7) => `frame:${id7}`)
464
464
  );
465
465
  return issues.length ? { success: false, issues, checks, uncheckedRefs } : { success: true, data, issues, checks, uncheckedRefs };
466
466
  }
@@ -561,9 +561,9 @@ function parseExperimentalClaimHistory(input) {
561
561
  if (!available.has(ref2)) problem("REF.LOCAL_RESOLUTION", path, `Undeclared local reference: ${ref2}`);
562
562
  else if (owner && claims.has(ref2)) graph.get(owner)?.add(ref2);
563
563
  }
564
- function refs(values2, path, owner) {
564
+ function refs(values3, path, owner) {
565
565
  const seen = /* @__PURE__ */ new Set();
566
- for (const [i, ref2] of values2.entries()) {
566
+ for (const [i, ref2] of values3.entries()) {
567
567
  if (seen.has(ref2)) problem("REF.UNIQUE_ID", `${path}/${i}`, "Reference is repeated.");
568
568
  seen.add(ref2);
569
569
  resolve(ref2, `${path}/${i}`, owner);
@@ -1438,8 +1438,8 @@ function observationContextJsonSchema() {
1438
1438
  }
1439
1439
 
1440
1440
  // src/experimental/v2/context.ts
1441
- function contextAssertions(entity2) {
1442
- return Object.entries(entity2.fields).flatMap(
1441
+ function contextAssertions(entity3) {
1442
+ return Object.entries(entity3.fields).flatMap(
1443
1443
  ([field, assertions]) => (assertions ?? []).map((assertion) => ({
1444
1444
  field,
1445
1445
  assertion
@@ -1453,7 +1453,7 @@ function parseObservationContext(input) {
1453
1453
  rulesetVersion: "0.1.0"
1454
1454
  };
1455
1455
  const issues = [];
1456
- const error = (code, pointer5, message) => issues.push({ code, stage: "semantic", pointer: pointer5, message });
1456
+ const error = (code, pointer6, message) => issues.push({ code, stage: "semantic", pointer: pointer6, message });
1457
1457
  if (!parsed.success)
1458
1458
  return {
1459
1459
  success: false,
@@ -1475,12 +1475,12 @@ function parseObservationContext(input) {
1475
1475
  const data = parsed.data;
1476
1476
  const entities = /* @__PURE__ */ new Map();
1477
1477
  const relativeGraph = /* @__PURE__ */ new Map();
1478
- for (const [i, entity2] of data.entities.entries()) {
1479
- const key2 = `${entity2.kind}:${entity2.id}`;
1478
+ for (const [i, entity3] of data.entities.entries()) {
1479
+ const key2 = `${entity3.kind}:${entity3.id}`;
1480
1480
  if (entities.has(key2))
1481
1481
  error("REF.UNIQUE_ID", `/entities/${i}/id`, "Duplicate entity identity.");
1482
- entities.set(key2, entity2);
1483
- if (entity2.kind === "temporal") relativeGraph.set(entity2.id, /* @__PURE__ */ new Set());
1482
+ entities.set(key2, entity3);
1483
+ if (entity3.kind === "temporal") relativeGraph.set(entity3.id, /* @__PURE__ */ new Set());
1484
1484
  }
1485
1485
  function time(value, path) {
1486
1486
  const found = [];
@@ -1493,9 +1493,9 @@ function parseObservationContext(input) {
1493
1493
  );
1494
1494
  const unchecked = /* @__PURE__ */ new Set([data.observationRef.sha256]);
1495
1495
  if (data.acquisitionRef) unchecked.add(data.acquisitionRef.sha256);
1496
- for (const [i, entity2] of data.entities.entries()) {
1496
+ for (const [i, entity3] of data.entities.entries()) {
1497
1497
  const path = `/entities/${i}`;
1498
- const assertions = contextAssertions(entity2);
1498
+ const assertions = contextAssertions(entity3);
1499
1499
  const ids = /* @__PURE__ */ new Set();
1500
1500
  for (const { field, assertion } of assertions) {
1501
1501
  const p = `${path}/fields/${field}`;
@@ -1528,8 +1528,8 @@ function parseObservationContext(input) {
1528
1528
  "Context entity reference does not resolve."
1529
1529
  );
1530
1530
  if (field === "placeIds") {
1531
- for (const id5 of content.value)
1532
- if (!entities.has(`place:${id5}`))
1531
+ for (const id7 of content.value)
1532
+ if (!entities.has(`place:${id7}`))
1533
1533
  error(
1534
1534
  "REF.LOCAL_RESOLUTION",
1535
1535
  p,
@@ -1552,7 +1552,7 @@ function parseObservationContext(input) {
1552
1552
  p,
1553
1553
  "Relative date anchor does not resolve."
1554
1554
  );
1555
- relativeGraph.get(entity2.id)?.add(relative2.anchorTemporalId);
1555
+ relativeGraph.get(entity3.id)?.add(relative2.anchorTemporalId);
1556
1556
  if (relative2.relation === "during" && relative2.offset)
1557
1557
  error(
1558
1558
  "TIME.RELATIVE_OFFSET",
@@ -1608,7 +1608,7 @@ function parseObservationContext(input) {
1608
1608
  }
1609
1609
  }
1610
1610
  const selectedFields = /* @__PURE__ */ new Set();
1611
- for (const selection of entity2.selections ?? []) {
1611
+ for (const selection of entity3.selections ?? []) {
1612
1612
  const p = `${path}/selections`;
1613
1613
  if (selectedFields.has(selection.field))
1614
1614
  error(
@@ -1625,9 +1625,9 @@ function parseObservationContext(input) {
1625
1625
  );
1626
1626
  if (new Set(selection.consideredAssertionIds).size !== selection.consideredAssertionIds.length)
1627
1627
  error("REF.UNIQUE_ID", p, "Considered assertions are repeated.");
1628
- for (const id5 of selection.consideredAssertionIds)
1628
+ for (const id7 of selection.consideredAssertionIds)
1629
1629
  if (!assertions.some(
1630
- (a) => a.field === selection.field && a.assertion.id === id5
1630
+ (a) => a.field === selection.field && a.assertion.id === id7
1631
1631
  ))
1632
1632
  error(
1633
1633
  "REF.FIELD_MISMATCH",
@@ -1661,7 +1661,7 @@ function parseObservationContext(input) {
1661
1661
  unchecked.add(selection.methodRef);
1662
1662
  }
1663
1663
  const measurements = /* @__PURE__ */ new Set();
1664
- for (const link of entity2.measurements ?? []) {
1664
+ for (const link of entity3.measurements ?? []) {
1665
1665
  if (measurements.has(link.id))
1666
1666
  error(
1667
1667
  "REF.UNIQUE_ID",
@@ -1882,9 +1882,9 @@ function parseContextClaimHistory(input) {
1882
1882
  );
1883
1883
  else if (owner && claims.has(ref2)) graph.get(owner)?.add(ref2);
1884
1884
  }
1885
- function refs(values2, path, owner) {
1885
+ function refs(values3, path, owner) {
1886
1886
  const seen = /* @__PURE__ */ new Set();
1887
- for (const [i, ref2] of values2.entries()) {
1887
+ for (const [i, ref2] of values3.entries()) {
1888
1888
  if (seen.has(ref2))
1889
1889
  problem("REF.UNIQUE_ID", `${path}/${i}`, "Reference is repeated.");
1890
1890
  seen.add(ref2);
@@ -2041,7 +2041,880 @@ function parseContextClaimHistory(input) {
2041
2041
  )
2042
2042
  };
2043
2043
  }
2044
+ var WitnessCategorySchema = z.enum([
2045
+ "military_pilot",
2046
+ "military_aircrew",
2047
+ "military_ground",
2048
+ "military_naval",
2049
+ "military_radar_operator",
2050
+ "military_other",
2051
+ "commercial_pilot",
2052
+ "commercial_aircrew",
2053
+ "private_pilot",
2054
+ "air_traffic_controller",
2055
+ "aviation_other",
2056
+ "government_official",
2057
+ "elected_official",
2058
+ "intelligence_officer",
2059
+ "law_enforcement",
2060
+ "scientist",
2061
+ "astronomer",
2062
+ "meteorologist",
2063
+ "engineer",
2064
+ "medical_professional",
2065
+ "maritime",
2066
+ "civilian",
2067
+ "civilian_group",
2068
+ "anonymous",
2069
+ "unknown"
2070
+ ]).describe("Professional/role category of a witness.");
2071
+ var CredibilityFactorSchema = z.enum([
2072
+ "professional_training",
2073
+ "official_capacity",
2074
+ "sworn_statement",
2075
+ "contemporaneous_record",
2076
+ "corroborating_witnesses",
2077
+ "corroborating_evidence",
2078
+ "consistent_account",
2079
+ "no_apparent_motive",
2080
+ "reputation_risk",
2081
+ "security_clearance"
2082
+ ]).describe("A factor strengthening witness credibility.");
2083
+ var CredibilityDetractorSchema = z.enum([
2084
+ "anonymous",
2085
+ "inconsistent_account",
2086
+ "delayed_report",
2087
+ "known_fabricator",
2088
+ "financial_motive",
2089
+ "single_witness",
2090
+ "impaired_state",
2091
+ "recovered_memory"
2092
+ ]).describe("A factor weakening witness credibility.");
2093
+ var WitnessCredibilitySchema = z.object({
2094
+ // The former `CredibilityRating` was byte-identical to the qualitative
2095
+ // `ConfidenceLevel`; it is now the single shared scale (DRY #1).
2096
+ rating: ConfidenceLevelSchema.optional(),
2097
+ factors: z.array(CredibilityFactorSchema).optional(),
2098
+ detractors: z.array(CredibilityDetractorSchema).optional(),
2099
+ isProfessionalObserver: z.boolean().optional().describe("Whether the witness is a trained observer (pilot, astronomer, military)."),
2100
+ hasAviationExperience: z.boolean().optional().describe("Whether the witness has aviation experience."),
2101
+ hasMilitaryExperience: z.boolean().optional().describe("Whether the witness has military experience."),
2102
+ hasScientificBackground: z.boolean().optional().describe("Whether the witness has a scientific background."),
2103
+ hasPriorUAPKnowledge: z.boolean().optional().describe("Whether the witness had prior knowledge of or interest in UAP before the observation."),
2104
+ wasSkepticPrior: z.boolean().optional().describe("Whether the witness was a skeptic before the observation."),
2105
+ underOathTestimony: z.boolean().optional().describe("Whether the testimony was given under oath."),
2106
+ polygraphAdministered: z.boolean().optional().describe("Whether a polygraph was administered."),
2107
+ polygraphPassed: z.boolean().optional().describe("Whether the witness passed the polygraph."),
2108
+ consistentTestimony: z.boolean().optional().describe("Whether the account has remained consistent across retellings."),
2109
+ willingToBeIdentified: z.boolean().optional().describe("Whether the witness is willing to be publicly identified."),
2110
+ notes: z.string().optional().describe("Free-text context about the credibility assessment.")
2111
+ }).meta({ id: "WitnessCredibility" }).describe("Structured assessment of a witness's credibility (rating, factors, detractors).");
2112
+
2113
+ // src/extensions/testimony/witness.ts
2114
+ var SecurityClearanceSchema = z.enum(["none", "confidential", "secret", "top_secret", "sci", "unknown"]).describe("Security clearance level held by a witness.");
2115
+ var WitnessSchema = z.object({
2116
+ witnessId: z.string().describe("Stable unique identifier for this witness."),
2117
+ category: WitnessCategorySchema,
2118
+ anonymous: z.boolean().describe("Whether the witness\u2019s identity is withheld."),
2119
+ publicName: z.string().optional().describe("Witness\u2019s name as publicly known, when not anonymous."),
2120
+ pseudonym: z.string().optional().describe("Pseudonym used when the witness is anonymous."),
2121
+ role: z.string().optional().describe('Witness\u2019s role at the time (e.g. "F/A-18F pilot", "radar operator").'),
2122
+ organization: z.string().optional().describe("Organization the witness belonged to at the time."),
2123
+ experienceYears: z.number().optional().describe("Years of relevant professional experience."),
2124
+ securityClearance: SecurityClearanceSchema.optional(),
2125
+ credibility: WitnessCredibilitySchema.optional(),
2126
+ statementSummary: z.string().optional().describe("Brief summary of what the witness reported."),
2127
+ interviewAvailable: z.boolean().optional().describe("Whether a recorded interview with the witness exists."),
2128
+ writtenReportAvailable: z.boolean().optional().describe("Whether a written report from the witness exists.")
2129
+ }).meta({ id: "Witness" }).describe("A person who reported or corroborated an observation.");
2130
+ var TemporalCertaintySchema = z.enum(["exact", "approximate", "estimated", "unknown"]).describe("Confidence in a date or time value \u2014 the single certainty scale for all temporal values.");
2131
+ var ChainOfCustodySchema = z.enum([
2132
+ "verified",
2133
+ "partial",
2134
+ "unverified",
2135
+ "government_held",
2136
+ "private_held",
2137
+ "lost",
2138
+ "destroyed",
2139
+ "classified",
2140
+ "unknown"
2141
+ ]).describe("Custody status of an evidence item.");
2142
+ var CustodyActionSchema = z.enum([
2143
+ "creation",
2144
+ "collection",
2145
+ "transfer",
2146
+ "storage",
2147
+ "analysis",
2148
+ "release",
2149
+ "classification",
2150
+ "destruction",
2151
+ "loss",
2152
+ "recovery",
2153
+ "other"
2154
+ ]).describe("An action recorded in a chain-of-custody entry.");
2155
+ var CustodyEntrySchema = z.object({
2156
+ entryId: z.string().describe("Stable unique identifier for this custody entry."),
2157
+ date: z.string().describe("When the custody event occurred (ISO date)."),
2158
+ action: CustodyActionSchema,
2159
+ from: z.string().optional().describe("Party that held the evidence before this event."),
2160
+ to: z.string().optional().describe("Party that held the evidence after this event."),
2161
+ location: z.string().optional().describe("Where the custody event took place."),
2162
+ reference: z.string().optional().describe("Document or record substantiating the event (e.g. transfer receipt, log entry)."),
2163
+ notes: z.string().optional().describe("Free-text context about the event.")
2164
+ }).meta({ id: "CustodyEntry" }).describe("A single custody event for an evidence item.");
2165
+ z.object({
2166
+ evidenceId: z.string().describe("Identifier of the evidence item this custody history belongs to."),
2167
+ status: ChainOfCustodySchema,
2168
+ entries: z.array(CustodyEntrySchema)
2169
+ }).meta({ id: "ChainOfCustodyRecord" }).describe("The full custody history for a piece of evidence.");
2170
+
2171
+ // src/extensions/testimony/statement.ts
2172
+ var TestimonyContextSchema = z.enum([
2173
+ "sworn_affidavit",
2174
+ "congressional_testimony",
2175
+ "deposition",
2176
+ "official_interview",
2177
+ "written_statement",
2178
+ "recorded_interview",
2179
+ "informal_account",
2180
+ "anonymous_tip",
2181
+ "whistleblower_disclosure"
2182
+ ]).describe("The setting in which testimony was given.");
2183
+ var TestimonyDateSchema = z.object({
2184
+ date: z.string().describe("When the testimony was given (ISO date)."),
2185
+ certainty: TemporalCertaintySchema
2186
+ }).meta({ id: "TestimonyDate" }).describe("When testimony was given, with its certainty.");
2187
+ z.object({
2188
+ statementId: z.string().describe('Stable id, addressable by a claim `evidenceRef` ("testimony:<statementId>").'),
2189
+ witness: WitnessSchema,
2190
+ context: TestimonyContextSchema,
2191
+ date: TestimonyDateSchema,
2192
+ content: z.string().optional().describe("Full text of the statement, when available."),
2193
+ summary: z.string().optional().describe("Brief summary of what the statement asserts."),
2194
+ sourceDocument: SourceReferenceSchema.optional(),
2195
+ chainOfCustody: ChainOfCustodySchema.optional(),
2196
+ additionalEvidenceIds: z.array(z.string()).optional().describe("Ids of other evidence items the statement references or supports.")
2197
+ }).meta({ id: "TestimonyStatement" }).describe("A single witness statement, its context, and supporting documentation.");
2198
+
2199
+ // src/experimental/v2/research-entities-schema.ts
2200
+ var text6 = z.string().min(1).regex(/\S/);
2201
+ var id5 = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/);
2202
+ var sourceRef3 = z.string().regex(/^(source|product):[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/);
2203
+ var provenance3 = SourceProvenanceSchema.extend({ sourceRef: sourceRef3 });
2204
+ var RESEARCH_ENTITIES_SCHEMA_ID = "urn:disclosureos:experimental:research-entities:0.1.0";
2205
+ function values2(schema) {
2206
+ return z.array(
2207
+ z.strictObject({
2208
+ id: id5.describe(
2209
+ "Assertion identity within this entity, independent of array order."
2210
+ ),
2211
+ content: z.union([
2212
+ z.strictObject({
2213
+ state: z.literal("known"),
2214
+ value: schema,
2215
+ provenance: provenance3,
2216
+ originalWording: text6.optional()
2217
+ }),
2218
+ z.strictObject({
2219
+ state: z.literal("approximate"),
2220
+ value: schema,
2221
+ precision: text6,
2222
+ provenance: provenance3,
2223
+ originalWording: text6.optional()
2224
+ }),
2225
+ z.strictObject({
2226
+ state: z.literal("unknown"),
2227
+ reason: z.enum(["not_recorded", "not_collected", "unavailable"])
2228
+ }),
2229
+ z.strictObject({ state: z.literal("redacted"), reason: text6 }),
2230
+ z.strictObject({
2231
+ state: z.literal("unmapped"),
2232
+ originalWording: text6,
2233
+ provenance: provenance3
2234
+ })
2235
+ ])
2236
+ })
2237
+ ).min(1).optional();
2238
+ }
2239
+ var timeContextReference = ContextReferenceSchema.extend({
2240
+ target: z.union([
2241
+ ContextTargetSchema.options[0],
2242
+ ContextTargetSchema.options[5]
2243
+ ])
2244
+ }).describe(
2245
+ "Temporal or event context for a qualification, not an arbitrary object attribute."
2246
+ );
2247
+ var relevantTime = z.union([
2248
+ z.strictObject({ kind: z.literal("calendar"), value: EventTimeValueSchema }),
2249
+ z.strictObject({
2250
+ kind: z.literal("context"),
2251
+ reference: timeContextReference
2252
+ }),
2253
+ z.strictObject({ kind: z.literal("unknown"), reason: text6 })
2254
+ ]);
2255
+ var qualification = (value) => z.strictObject({ value, relevantTime });
2256
+ var ResearchWitnessFields = {
2257
+ publicIdentity: values2(
2258
+ z.discriminatedUnion("kind", [
2259
+ z.strictObject({ kind: z.literal("public_name"), display: text6 }),
2260
+ z.strictObject({ kind: z.literal("pseudonym"), display: text6 }),
2261
+ z.strictObject({ kind: z.literal("withheld"), display: text6 })
2262
+ ])
2263
+ ),
2264
+ anonymous: values2(z.boolean()),
2265
+ willingToBeIdentified: values2(z.boolean()),
2266
+ category: values2(qualification(WitnessCategorySchema)),
2267
+ role: values2(qualification(text6)),
2268
+ organization: values2(qualification(text6)),
2269
+ experienceYears: values2(qualification(z.number().min(0))),
2270
+ securityClearance: values2(qualification(SecurityClearanceSchema)),
2271
+ isProfessionalObserver: values2(qualification(z.boolean())),
2272
+ hasAviationExperience: values2(qualification(z.boolean())),
2273
+ hasMilitaryExperience: values2(qualification(z.boolean())),
2274
+ hasScientificBackground: values2(qualification(z.boolean())),
2275
+ hasPriorUAPKnowledge: values2(qualification(z.boolean())),
2276
+ wasSkepticPrior: values2(qualification(z.boolean())),
2277
+ description: values2(text6)
2278
+ };
2279
+ var ResearchAccountFields = {
2280
+ speakerWitnessIds: values2(z.array(id5).min(1)),
2281
+ recorder: values2(text6),
2282
+ context: values2(TestimonyContextSchema),
2283
+ recordedTime: values2(EventTimeValueSchema),
2284
+ dateCertainty: values2(
2285
+ z.enum(["exact", "approximate", "estimated", "unknown"])
2286
+ ),
2287
+ eventContext: values2(ContextReferenceSchema),
2288
+ content: values2(text6),
2289
+ summary: values2(z.strictObject({ text: text6, summarizedBy: text6 })),
2290
+ sourceDocument: values2(sourceRef3),
2291
+ interviewAvailable: values2(z.boolean()),
2292
+ writtenReportAvailable: values2(z.boolean()),
2293
+ underOath: values2(z.boolean()),
2294
+ custodyStatus: values2(ChainOfCustodySchema),
2295
+ supportRefs: values2(z.array(sourceRef3).min(1))
2296
+ };
2297
+ var ResearchProcedureFields = {
2298
+ procedureType: values2(z.literal("polygraph")),
2299
+ witnessId: values2(id5),
2300
+ accountId: values2(id5),
2301
+ administered: values2(z.boolean()),
2302
+ passed: values2(z.boolean()),
2303
+ performedAt: values2(EventTimeValueSchema),
2304
+ context: values2(text6),
2305
+ sourceDocument: values2(sourceRef3)
2306
+ };
2307
+ var ResearchWitnessGroupFields = {
2308
+ witnessIds: values2(z.array(id5).min(1)),
2309
+ reportedCount: values2(z.number().int().min(0)),
2310
+ categories: values2(z.array(WitnessCategorySchema).min(1)),
2311
+ militaryWitnesses: values2(z.boolean()),
2312
+ aviationWitnesses: values2(z.boolean()),
2313
+ professionalObservers: values2(z.boolean()),
2314
+ descriptions: values2(z.array(text6).min(1))
2315
+ };
2316
+ for (const fields of [
2317
+ ResearchWitnessFields,
2318
+ ResearchAccountFields,
2319
+ ResearchProcedureFields,
2320
+ ResearchWitnessGroupFields
2321
+ ])
2322
+ for (const [key2, schema] of Object.entries(fields))
2323
+ fields[key2] = schema.describe(
2324
+ `Sourced ${key2.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase()} assertions. Alternatives and unknowns are retained; supplied does not mean verified.`
2325
+ );
2326
+ function entity2(kind, fields) {
2327
+ return z.strictObject({
2328
+ kind: z.literal(kind),
2329
+ id: id5,
2330
+ fields: z.strictObject(fields)
2331
+ });
2332
+ }
2333
+ var ResearchEntitySchema = z.discriminatedUnion("kind", [
2334
+ entity2("witness", ResearchWitnessFields),
2335
+ entity2("account", ResearchAccountFields),
2336
+ entity2("procedure", ResearchProcedureFields),
2337
+ entity2("witness_group", ResearchWitnessGroupFields)
2338
+ ]);
2339
+ var ResearchEntitiesSchema = z.strictObject({
2340
+ kind: z.literal("research_entities"),
2341
+ schemaVersion: z.literal("0.1.0"),
2342
+ id: id5,
2343
+ observationRef: ObservationSnapshotRefSchema,
2344
+ contextRefs: z.array(
2345
+ DocumentSnapshotRefSchema.extend({
2346
+ schemaId: z.literal(OBSERVATION_CONTEXT_SCHEMA_ID)
2347
+ })
2348
+ ),
2349
+ recordedAt: instantString,
2350
+ recordedBy: text6,
2351
+ entities: z.array(ResearchEntitySchema).min(1)
2352
+ }).describe(
2353
+ "Public witness, account, procedure and aggregate declarations. Private identity mappings and contact fields belong outside this exchange document. No consent or credibility is inferred."
2354
+ );
2355
+ function target2(kind, fields) {
2356
+ return z.strictObject({
2357
+ kind: z.literal(kind),
2358
+ id: id5,
2359
+ field: z.enum(Object.keys(fields)).optional()
2360
+ });
2361
+ }
2362
+ var ResearchEntityTargetSchema = z.discriminatedUnion("kind", [
2363
+ target2("witness", ResearchWitnessFields),
2364
+ target2("account", ResearchAccountFields),
2365
+ target2("procedure", ResearchProcedureFields),
2366
+ target2("witness_group", ResearchWitnessGroupFields)
2367
+ ]);
2368
+ var ResearchEntityReferenceSchema = z.strictObject({
2369
+ document: DocumentSnapshotRefSchema.extend({
2370
+ schemaId: z.literal(RESEARCH_ENTITIES_SCHEMA_ID)
2371
+ }),
2372
+ target: ResearchEntityTargetSchema
2373
+ });
2374
+ var ResearchEntityAssertionReferenceSchema = ResearchEntityReferenceSchema.extend({ assertionId: id5 });
2375
+ function researchEntitiesJsonSchema() {
2376
+ return {
2377
+ ...z.toJSONSchema(ResearchEntitiesSchema, {
2378
+ target: "draft-2020-12",
2379
+ reused: "ref"
2380
+ }),
2381
+ $id: RESEARCH_ENTITIES_SCHEMA_ID
2382
+ };
2383
+ }
2384
+
2385
+ // src/experimental/v2/research-entities.ts
2386
+ function researchEntityAssertions(entity3) {
2387
+ return Object.entries(entity3.fields).flatMap(
2388
+ ([field, list]) => (list ?? []).map((assertion) => ({
2389
+ field,
2390
+ assertion
2391
+ }))
2392
+ );
2393
+ }
2394
+ function researchEntityContextReferences(entity3) {
2395
+ return researchEntityAssertions(entity3).flatMap(({ field, assertion }) => {
2396
+ const value = assertion.content.value;
2397
+ if (field === "eventContext" && value)
2398
+ return [value];
2399
+ return value?.relevantTime?.kind === "context" ? [value.relevantTime.reference] : [];
2400
+ });
2401
+ }
2402
+ function parseResearchEntities(input) {
2403
+ const parsed = ResearchEntitiesSchema.safeParse(input);
2404
+ const contract = {
2405
+ schemaId: RESEARCH_ENTITIES_SCHEMA_ID,
2406
+ rulesetVersion: "0.1.0"
2407
+ };
2408
+ if (!parsed.success)
2409
+ return {
2410
+ success: false,
2411
+ contract,
2412
+ checks: {
2413
+ structural: "failed",
2414
+ semantic: "not_checked",
2415
+ profile: "not_checked",
2416
+ external: "not_checked"
2417
+ },
2418
+ uncheckedRefs: [],
2419
+ issues: parsed.error.issues.map((i) => ({
2420
+ code: "STRUCT.VALUE",
2421
+ stage: "structural",
2422
+ pointer: "/" + i.path.join("/"),
2423
+ message: i.message
2424
+ }))
2425
+ };
2426
+ const data = parsed.data, issues = [];
2427
+ const problem = (code, pointer6, message) => issues.push({ code, stage: "semantic", pointer: pointer6, message });
2428
+ const snapshots = new Set(data.contextRefs.map((r) => JSON.stringify(r)));
2429
+ if (snapshots.size !== data.contextRefs.length)
2430
+ problem(
2431
+ "REF.UNIQUE_ID",
2432
+ "/contextRefs",
2433
+ "Context snapshot references repeat."
2434
+ );
2435
+ const unchecked = /* @__PURE__ */ new Set([
2436
+ data.observationRef.sha256,
2437
+ ...data.contextRefs.map((r) => r.sha256)
2438
+ ]);
2439
+ const identities = /* @__PURE__ */ new Set();
2440
+ for (const [i, e] of data.entities.entries()) {
2441
+ const key2 = `${e.kind}:${e.id}`;
2442
+ if (identities.has(key2))
2443
+ problem(
2444
+ "REF.UNIQUE_ID",
2445
+ `/entities/${i}/id`,
2446
+ "Entity identity repeats within its kind."
2447
+ );
2448
+ identities.add(key2);
2449
+ }
2450
+ function time(v, p) {
2451
+ const found = [];
2452
+ checkTime(v, p, found);
2453
+ found.forEach((i) => problem(i.code, i.pointer, i.message));
2454
+ }
2455
+ time(
2456
+ { kind: "instant", value: data.recordedAt},
2457
+ "/recordedAt"
2458
+ );
2459
+ for (const [i, e] of data.entities.entries()) {
2460
+ const ep = `/entities/${i}`, ids = /* @__PURE__ */ new Set();
2461
+ for (const { field, assertion: a } of researchEntityAssertions(e)) {
2462
+ const p = `${ep}/fields/${field}`;
2463
+ if (ids.has(a.id))
2464
+ problem("REF.UNIQUE_ID", p, "Assertion IDs repeat within this entity.");
2465
+ ids.add(a.id);
2466
+ const prov = a.content.provenance;
2467
+ if (prov) {
2468
+ unchecked.add(prov.sourceRef);
2469
+ if (prov.locator?.kind === "time_range" && prov.locator.endSeconds < prov.locator.startSeconds)
2470
+ problem("TIME.INTERVAL", p, "Source locator end precedes its start.");
2471
+ }
2472
+ const value = a.content.value;
2473
+ if (value === void 0) continue;
2474
+ if (field === "recordedTime" || field === "performedAt")
2475
+ time(value, p);
2476
+ const relevant = value.relevantTime;
2477
+ if (relevant?.kind === "calendar") time(relevant.value, p);
2478
+ const targetKind = field === "speakerWitnessIds" || field === "witnessIds" || field === "witnessId" ? "witness" : field === "accountId" ? "account" : void 0;
2479
+ if (targetKind) {
2480
+ const refs = Array.isArray(value) ? value : [value];
2481
+ if (new Set(refs).size !== refs.length)
2482
+ problem("REF.UNIQUE_ID", p, "Typed local links repeat.");
2483
+ for (const id7 of refs)
2484
+ if (!identities.has(`${targetKind}:${id7}`))
2485
+ problem("REF.ENTITY", p, "Typed local entity does not exist.");
2486
+ }
2487
+ if (field === "sourceDocument") unchecked.add(value);
2488
+ if (field === "supportRefs") {
2489
+ const refs = value;
2490
+ if (new Set(refs).size !== refs.length)
2491
+ problem("REF.UNIQUE_ID", p, "Support references repeat.");
2492
+ refs.forEach((r) => unchecked.add(r));
2493
+ }
2494
+ }
2495
+ for (const ref2 of researchEntityContextReferences(e))
2496
+ if (!snapshots.has(JSON.stringify(ref2.document)))
2497
+ problem(
2498
+ "REF.LOCAL_RESOLUTION",
2499
+ ep,
2500
+ "Context reference must select a declared snapshot."
2501
+ );
2502
+ }
2503
+ const validation = {
2504
+ contract,
2505
+ issues,
2506
+ uncheckedRefs: [...unchecked],
2507
+ checks: {
2508
+ structural: "passed",
2509
+ semantic: issues.length ? "failed" : "passed",
2510
+ profile: "not_checked",
2511
+ external: "not_checked"
2512
+ }
2513
+ };
2514
+ return issues.length ? { ...validation, success: false } : { ...validation, success: true, data };
2515
+ }
2516
+ var text7 = z.string().min(1).regex(/\S/, "must contain non-whitespace text");
2517
+ var id6 = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/);
2518
+ var claimRef3 = z.string().regex(/^claim:[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/);
2519
+ var inputRef3 = z.string().regex(
2520
+ /^(?:claim|source|product|assertion|measurement):[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/
2521
+ );
2522
+ var ResearchClaimSubjectSchema = z.discriminatedUnion("kind", [
2523
+ z.strictObject({ kind: z.literal("observation") }),
2524
+ z.strictObject({
2525
+ kind: z.literal("entity"),
2526
+ reference: ResearchEntityReferenceSchema
2527
+ }),
2528
+ z.strictObject({
2529
+ kind: z.literal("context"),
2530
+ reference: ContextReferenceSchema
2531
+ }),
2532
+ z.strictObject({ kind: z.literal("measurement"), measurementId: id6 })
2533
+ ]);
2534
+ var WitnessReviewSchema = z.strictObject({
2535
+ rating: ConfidenceLevelSchema.optional(),
2536
+ factors: z.array(CredibilityFactorSchema).optional().describe(
2537
+ "Reviewer-selected factor labels; no built-in weighting or validation of their truth."
2538
+ ),
2539
+ detractors: z.array(CredibilityDetractorSchema).optional().describe(
2540
+ "Retained vocabulary for attributable reviews. Anonymity never adds a penalty automatically."
2541
+ ),
2542
+ consistentTestimony: z.enum(["consistent", "inconsistent", "unknown"]).optional(),
2543
+ multipleIndependent: z.enum(["independent", "not_independent", "unknown"]).optional(),
2544
+ notes: text7.optional()
2545
+ }).describe(
2546
+ "Attributable interpretation, separate from sourced qualifications; requires explicit inputs."
2547
+ );
2548
+ var common3 = {
2549
+ id: id6,
2550
+ recordedAt: instantString,
2551
+ topic: text7,
2552
+ subject: ResearchClaimSubjectSchema,
2553
+ supersedes: z.array(claimRef3).min(1).optional()
2554
+ };
2555
+ var ResearchSourceStatementSchema = z.strictObject({
2556
+ ...common3,
2557
+ kind: z.literal("source_assertion"),
2558
+ text: text7,
2559
+ reportedLevel: text7.optional(),
2560
+ provenance: ObservationAssertionSchema.options[0].shape.provenance
2561
+ });
2562
+ var assessment3 = {
2563
+ ...common3,
2564
+ kind: z.literal("assessment"),
2565
+ inputRefs: z.array(inputRef3),
2566
+ contextInputRefs: z.array(ContextAssertionReferenceSchema).optional(),
2567
+ entityInputRefs: z.array(ResearchEntityAssertionReferenceSchema).optional(),
2568
+ rationale: text7
2569
+ };
2570
+ var ResearchUnassessedClaimSchema = z.strictObject({
2571
+ ...assessment3,
2572
+ status: z.literal("unassessed")
2573
+ });
2574
+ var ResearchAssessedClaimSchema = z.strictObject({
2575
+ ...assessment3,
2576
+ status: z.literal("assessed"),
2577
+ outcome: z.enum(["reported", "confirmed", "absent", "inconclusive"]),
2578
+ evaluatedBy: text7,
2579
+ evaluatedAt: instantString,
2580
+ methodRef: z.string().regex(/^method:[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/),
2581
+ methodVersion: text7,
2582
+ confidence: z.number().min(0).max(1).optional(),
2583
+ witnessReview: WitnessReviewSchema.optional()
2584
+ });
2585
+ var ResearchHistoricalClaimSchema = z.union([
2586
+ ResearchSourceStatementSchema,
2587
+ ResearchUnassessedClaimSchema,
2588
+ ResearchAssessedClaimSchema
2589
+ ]);
2590
+ var RESEARCH_CLAIM_HISTORY_SCHEMA_ID = "urn:disclosureos:experimental:claim-history:0.3.0";
2591
+ var RESEARCH_CLAIM_HISTORY_RULESET_VERSION = "0.3.0";
2592
+ var ResearchClaimHistorySchema = z.strictObject({
2593
+ kind: z.literal("claim_history"),
2594
+ schemaVersion: z.literal("0.3.0"),
2595
+ id: id6,
2596
+ contextRefs: z.array(
2597
+ DocumentSnapshotRefSchema.extend({
2598
+ schemaId: z.literal(OBSERVATION_CONTEXT_SCHEMA_ID)
2599
+ })
2600
+ ),
2601
+ entityRefs: z.array(
2602
+ DocumentSnapshotRefSchema.extend({
2603
+ schemaId: z.literal(RESEARCH_ENTITIES_SCHEMA_ID)
2604
+ })
2605
+ ),
2606
+ observation: ExperimentalObservationSchema,
2607
+ claims: z.array(ResearchHistoricalClaimSchema),
2608
+ extensions: ExperimentalObservationSchema.shape.extensions
2609
+ });
2610
+ function researchClaimHistoryJsonSchema() {
2611
+ return {
2612
+ ...z.toJSONSchema(ResearchClaimHistorySchema, {
2613
+ target: "draft-2020-12",
2614
+ reused: "ref"
2615
+ }),
2616
+ $id: RESEARCH_CLAIM_HISTORY_SCHEMA_ID
2617
+ };
2618
+ }
2619
+
2620
+ // src/experimental/v2/research-claim-history.ts
2621
+ var point3 = (value) => ({
2622
+ kind: "instant",
2623
+ value,
2624
+ timeScale: "UTC"
2625
+ });
2626
+ var pointer5 = (path) => path.map((p) => `/${String(p).replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
2627
+ function parseResearchClaimHistory(input) {
2628
+ const contract = {
2629
+ kind: "claim_history",
2630
+ schemaId: RESEARCH_CLAIM_HISTORY_SCHEMA_ID,
2631
+ rulesetVersion: RESEARCH_CLAIM_HISTORY_RULESET_VERSION
2632
+ };
2633
+ const parsed = ResearchClaimHistorySchema.safeParse(input);
2634
+ if (!parsed.success)
2635
+ return {
2636
+ success: false,
2637
+ contract,
2638
+ checks: {
2639
+ structural: "failed",
2640
+ semantic: "not_checked",
2641
+ profile: "not_checked",
2642
+ external: "not_checked"
2643
+ },
2644
+ uncheckedRefs: [],
2645
+ issues: parsed.error.issues.map((issue) => ({
2646
+ code: "STRUCT.VALUE",
2647
+ stage: "structural",
2648
+ severity: "error",
2649
+ pointer: pointer5(issue.path),
2650
+ message: issue.message
2651
+ }))
2652
+ };
2653
+ const data = parsed.data;
2654
+ const observationResult = parseExperimentalObservation(data.observation);
2655
+ const issues = observationResult.issues.map(
2656
+ (issue) => ({ ...issue, pointer: `/observation${issue.pointer}` })
2657
+ );
2658
+ const problem = (code, path, message) => issues.push({
2659
+ code,
2660
+ stage: "semantic",
2661
+ severity: "error",
2662
+ pointer: path,
2663
+ message
2664
+ });
2665
+ const claims = /* @__PURE__ */ new Map();
2666
+ const graph = /* @__PURE__ */ new Map();
2667
+ const superseded = /* @__PURE__ */ new Set();
2668
+ const sources = new Map(
2669
+ data.observation.sources.map((item) => [`source:${item.id}`, item])
2670
+ );
2671
+ const products = new Map(
2672
+ data.observation.products.map((item) => [`product:${item.id}`, item])
2673
+ );
2674
+ const methods = new Map(
2675
+ data.observation.methods.map((item) => [`method:${item.id}`, item])
2676
+ );
2677
+ const measurements = new Set(
2678
+ data.observation.measurements.map((item) => `measurement:${item.id}`)
2679
+ );
2680
+ const available = /* @__PURE__ */ new Set([
2681
+ ...sources.keys(),
2682
+ ...products.keys(),
2683
+ ...measurements,
2684
+ ...data.observation.assertions.map((item) => `assertion:${item.id}`)
2685
+ ]);
2686
+ for (const [i, claim] of data.claims.entries()) {
2687
+ const ref2 = `claim:${claim.id}`;
2688
+ if (claims.has(ref2))
2689
+ problem(
2690
+ "REF.UNIQUE_ID",
2691
+ `/claims/${i}/id`,
2692
+ "Duplicate claim ID; each revision must have its own ID."
2693
+ );
2694
+ else {
2695
+ claims.set(ref2, claim);
2696
+ graph.set(ref2, /* @__PURE__ */ new Set());
2697
+ available.add(ref2);
2698
+ }
2699
+ }
2700
+ function instant(value, path) {
2701
+ const local = [];
2702
+ checkTime(point3(value), path, local);
2703
+ for (const issue of local)
2704
+ problem(issue.code, issue.pointer, issue.message);
2705
+ }
2706
+ function resolve(ref2, path, owner) {
2707
+ if (!available.has(ref2))
2708
+ problem(
2709
+ "REF.LOCAL_RESOLUTION",
2710
+ path,
2711
+ `Undeclared local reference: ${ref2}`
2712
+ );
2713
+ else if (owner && claims.has(ref2)) graph.get(owner)?.add(ref2);
2714
+ }
2715
+ function refs(values3, path, owner) {
2716
+ const seen = /* @__PURE__ */ new Set();
2717
+ for (const [i, ref2] of values3.entries()) {
2718
+ if (seen.has(ref2))
2719
+ problem("REF.UNIQUE_ID", `${path}/${i}`, "Reference is repeated.");
2720
+ seen.add(ref2);
2721
+ resolve(ref2, `${path}/${i}`, owner);
2722
+ }
2723
+ }
2724
+ const snapshots = new Set(data.contextRefs.map((r) => JSON.stringify(r)));
2725
+ if (snapshots.size !== data.contextRefs.length)
2726
+ problem(
2727
+ "REF.UNIQUE_ID",
2728
+ "/contextRefs",
2729
+ "Context snapshot references repeat."
2730
+ );
2731
+ for (const [i, claim] of data.claims.entries()) {
2732
+ const contextRefs = [
2733
+ ...claim.subject.kind === "context" ? [claim.subject.reference] : [],
2734
+ ...claim.kind === "assessment" ? claim.contextInputRefs ?? [] : []
2735
+ ];
2736
+ for (const ref2 of contextRefs)
2737
+ if (!snapshots.has(JSON.stringify(ref2.document)))
2738
+ problem(
2739
+ "REF.LOCAL_RESOLUTION",
2740
+ `/claims/${i}`,
2741
+ "Context reference must select a declared snapshot."
2742
+ );
2743
+ if (claim.kind === "assessment" && new Set((claim.contextInputRefs ?? []).map((r) => JSON.stringify(r))).size !== (claim.contextInputRefs ?? []).length)
2744
+ problem(
2745
+ "REF.UNIQUE_ID",
2746
+ `/claims/${i}/contextInputRefs`,
2747
+ "Context inputs repeat."
2748
+ );
2749
+ }
2750
+ const entitySnapshots = new Set(
2751
+ data.entityRefs.map((r) => JSON.stringify(r))
2752
+ );
2753
+ if (entitySnapshots.size !== data.entityRefs.length)
2754
+ problem("REF.UNIQUE_ID", "/entityRefs", "Entity snapshots repeat.");
2755
+ for (const [i, claim] of data.claims.entries()) {
2756
+ const refs2 = [
2757
+ ...claim.subject.kind === "entity" ? [claim.subject.reference] : [],
2758
+ ...claim.kind === "assessment" ? claim.entityInputRefs ?? [] : []
2759
+ ];
2760
+ for (const ref2 of refs2)
2761
+ if (!entitySnapshots.has(JSON.stringify(ref2.document)))
2762
+ problem(
2763
+ "REF.LOCAL_RESOLUTION",
2764
+ `/claims/${i}`,
2765
+ "Entity reference must select a declared snapshot."
2766
+ );
2767
+ if (claim.kind === "assessment") {
2768
+ if (new Set((claim.entityInputRefs ?? []).map((r) => JSON.stringify(r))).size !== (claim.entityInputRefs ?? []).length)
2769
+ problem(
2770
+ "REF.UNIQUE_ID",
2771
+ `/claims/${i}/entityInputRefs`,
2772
+ "Entity inputs repeat."
2773
+ );
2774
+ if (claim.status === "assessed" && claim.witnessReview) {
2775
+ if (claim.subject.kind !== "entity" || !["witness", "account", "witness_group", "procedure"].includes(
2776
+ claim.subject.reference.target.kind
2777
+ ))
2778
+ problem(
2779
+ "CLAIM.SUPERSESSION_SCOPE",
2780
+ `/claims/${i}/witnessReview`,
2781
+ "Witness review requires a typed research-entity subject."
2782
+ );
2783
+ if (claim.inputRefs.length + (claim.entityInputRefs?.length ?? 0) + (claim.contextInputRefs?.length ?? 0) === 0)
2784
+ problem(
2785
+ "REF.LOCAL_RESOLUTION",
2786
+ `/claims/${i}/witnessReview`,
2787
+ "Witness review requires explicit inputs."
2788
+ );
2789
+ }
2790
+ }
2791
+ }
2792
+ for (const [i, claim] of data.claims.entries()) {
2793
+ const path = `/claims/${i}`;
2794
+ const owner = `claim:${claim.id}`;
2795
+ instant(claim.recordedAt, `${path}/recordedAt`);
2796
+ if (claim.subject.kind === "measurement")
2797
+ resolve(
2798
+ `measurement:${claim.subject.measurementId}`,
2799
+ `${path}/subject/measurementId`
2800
+ );
2801
+ if (claim.supersedes) {
2802
+ refs(claim.supersedes, `${path}/supersedes`, owner);
2803
+ for (const [j, ref2] of claim.supersedes.entries()) {
2804
+ const previous = claims.get(ref2);
2805
+ if (!previous) continue;
2806
+ superseded.add(ref2);
2807
+ if (previous.kind !== claim.kind || previous.topic !== claim.topic || JSON.stringify(previous.subject) !== JSON.stringify(claim.subject)) {
2808
+ problem(
2809
+ "CLAIM.SUPERSESSION_SCOPE",
2810
+ `${path}/supersedes/${j}`,
2811
+ "A revision must retain the claim kind, topic, and subject. Record a different claim separately."
2812
+ );
2813
+ }
2814
+ if (previous.kind === "assessment" && previous.status === "assessed" && claim.kind === "assessment" && (claim.status !== "assessed" || previous.evaluatedBy !== claim.evaluatedBy)) {
2815
+ problem(
2816
+ "CLAIM.REVISION_ATTRIBUTION",
2817
+ `${path}/supersedes/${j}`,
2818
+ "An assessed revision must retain its evaluator; other evaluators record independent assessments."
2819
+ );
2820
+ }
2821
+ if (comparePoints(point3(previous.recordedAt), point3(claim.recordedAt)) > 0) {
2822
+ problem(
2823
+ "CLAIM.REVISION_ORDER",
2824
+ `${path}/recordedAt`,
2825
+ "A revision cannot be recorded before the statement it supersedes."
2826
+ );
2827
+ }
2828
+ }
2829
+ }
2830
+ if (claim.kind === "source_assertion") {
2831
+ resolve(claim.provenance.sourceRef, `${path}/provenance/sourceRef`);
2832
+ const source = sources.get(claim.provenance.sourceRef) ?? products.get(claim.provenance.sourceRef);
2833
+ if (source?.digest && claim.provenance.sourceDigest && source.digest.value !== claim.provenance.sourceDigest.value) {
2834
+ problem(
2835
+ "SOURCE.DIGEST_MISMATCH",
2836
+ `${path}/provenance/sourceDigest`,
2837
+ "Digest differs from the inventory declaration; neither is verified against bytes."
2838
+ );
2839
+ }
2840
+ const locator = claim.provenance.locator;
2841
+ if (locator?.kind === "time_range" && locator.endSeconds < locator.startSeconds)
2842
+ problem(
2843
+ "TIME.INTERVAL",
2844
+ `${path}/provenance/locator/endSeconds`,
2845
+ "Locator end precedes its start."
2846
+ );
2847
+ } else {
2848
+ refs(claim.inputRefs, `${path}/inputRefs`, owner);
2849
+ if (claim.status === "assessed") {
2850
+ instant(claim.evaluatedAt, `${path}/evaluatedAt`);
2851
+ if (comparePoints(point3(claim.evaluatedAt), point3(claim.recordedAt)) > 0)
2852
+ problem(
2853
+ "CLAIM.EVALUATION_ORDER",
2854
+ `${path}/evaluatedAt`,
2855
+ "Evaluation cannot occur after the assessment was recorded."
2856
+ );
2857
+ const method = methods.get(claim.methodRef);
2858
+ if (!method)
2859
+ problem(
2860
+ "REF.LOCAL_RESOLUTION",
2861
+ `${path}/methodRef`,
2862
+ "Assessment method is not declared in the Observation inventory."
2863
+ );
2864
+ else if (method.version !== claim.methodVersion)
2865
+ problem(
2866
+ "METHOD.VERSION_MISMATCH",
2867
+ `${path}/methodVersion`,
2868
+ "Assessment method version differs from its inventory declaration."
2869
+ );
2870
+ }
2871
+ }
2872
+ }
2873
+ const indegrees = new Map([...graph.keys()].map((ref2) => [ref2, 0]));
2874
+ for (const edges of graph.values())
2875
+ for (const ref2 of edges) indegrees.set(ref2, indegrees.get(ref2) + 1);
2876
+ const queue = [...indegrees].filter(([, degree]) => degree === 0).map(([ref2]) => ref2);
2877
+ for (let i = 0; i < queue.length; i++)
2878
+ for (const ref2 of graph.get(queue[i]) ?? []) {
2879
+ const degree = indegrees.get(ref2) - 1;
2880
+ indegrees.set(ref2, degree);
2881
+ if (degree === 0) queue.push(ref2);
2882
+ }
2883
+ if (queue.length !== graph.size)
2884
+ problem(
2885
+ "CLAIM.DEPENDENCY_CYCLE",
2886
+ "/claims",
2887
+ "Claim inputs and supersession must form an acyclic history."
2888
+ );
2889
+ const validation = {
2890
+ contract,
2891
+ issues,
2892
+ uncheckedRefs: [
2893
+ ...data.contextRefs.map((r) => r.sha256),
2894
+ ...data.entityRefs.map((r) => r.sha256),
2895
+ ...observationResult.uncheckedRefs,
2896
+ ...data.claims.flatMap((c) => [
2897
+ ...c.subject.kind === "context" ? [c.subject.reference.document.sha256] : [],
2898
+ ...c.kind === "assessment" ? (c.contextInputRefs ?? []).map((r) => r.document.sha256) : []
2899
+ ])
2900
+ ],
2901
+ checks: {
2902
+ structural: "passed",
2903
+ semantic: issues.length ? "failed" : "passed",
2904
+ profile: "not_checked",
2905
+ external: "not_checked"
2906
+ }
2907
+ };
2908
+ return issues.length ? { ...validation, success: false } : {
2909
+ ...validation,
2910
+ success: true,
2911
+ data,
2912
+ currentClaimRefs: [...claims.keys()].filter(
2913
+ (ref2) => !superseded.has(ref2)
2914
+ )
2915
+ };
2916
+ }
2044
2917
 
2045
- export { AssessedClaimSchema, CLAIM_HISTORY_RULESET_VERSION, CONTEXT_CLAIM_HISTORY_RULESET_VERSION, CONTEXT_CLAIM_HISTORY_SCHEMA_ID, ClaimSubjectSchema, ContextAssertionReferenceSchema, ContextAssessedClaimSchema, ContextClaimHistorySchema, ContextClaimSubjectSchema, ContextCollectionFields, ContextEntitySchema, ContextEnvironmentFields, ContextEventFields, ContextHistoricalClaimSchema, ContextMeasurementLinkSchema, ContextObjectFields, ContextPlaceFields, ContextPlatformFields, ContextReferenceSchema, ContextSourceStatementSchema, ContextTargetSchema, ContextTemporalFields, ContextUnassessedClaimSchema, DocumentSnapshotRefSchema, EXPERIMENTAL_CLAIM_HISTORY_SCHEMA_ID, EXPERIMENTAL_OBSERVATION_SCHEMA_ID, EventTimeIntervalSchema, EventTimePointSchema, EventTimeSchema, EventTimeValueSchema, ExperimentalClaimHistorySchema, ExperimentalObservationSchema, FramedPositionSchema, HistoricalClaimSchema, MeasuredQuantitySchema, OBSERVATION_CONTEXT_SCHEMA_ID, ObservationAssertionSchema, ObservationContextSchema, ObservationMeasurementSchema, ObservationMethodSchema, ObservationPositionSchema, ObservationProductSchema, ObservationSnapshotRefSchema, ObservationSourceSchema, ObservationTimeSchema, PRIMITIVES_SCHEMA_ID, PositionSchema, PositionValueSchema, PrimitiveRecordSchema, ProcessingActivitySchema, QuantitativeUncertaintySchema, ReferenceFrameSchema, SourceProvenanceSchema, SourceStatementSchema, UnassessedClaimSchema, ValueAssertionSchema, ValueSelectionSchema, compareUtcInstants, contextAssertions, contextClaimHistoryJsonSchema, experimentalClaimHistoryJsonSchema, experimentalObservationJsonSchema, observationContextJsonSchema, parseContextClaimHistory, parseExperimentalClaimHistory, parseExperimentalObservation, parseObservationContext, parsePrimitiveRecord, primitivesJsonSchema };
2918
+ export { AssessedClaimSchema, CLAIM_HISTORY_RULESET_VERSION, CONTEXT_CLAIM_HISTORY_RULESET_VERSION, CONTEXT_CLAIM_HISTORY_SCHEMA_ID, ClaimSubjectSchema, ContextAssertionReferenceSchema, ContextAssessedClaimSchema, ContextClaimHistorySchema, ContextClaimSubjectSchema, ContextCollectionFields, ContextEntitySchema, ContextEnvironmentFields, ContextEventFields, ContextHistoricalClaimSchema, ContextMeasurementLinkSchema, ContextObjectFields, ContextPlaceFields, ContextPlatformFields, ContextReferenceSchema, ContextSourceStatementSchema, ContextTargetSchema, ContextTemporalFields, ContextUnassessedClaimSchema, DocumentSnapshotRefSchema, EXPERIMENTAL_CLAIM_HISTORY_SCHEMA_ID, EXPERIMENTAL_OBSERVATION_SCHEMA_ID, EventTimeIntervalSchema, EventTimePointSchema, EventTimeSchema, EventTimeValueSchema, ExperimentalClaimHistorySchema, ExperimentalObservationSchema, FramedPositionSchema, HistoricalClaimSchema, MeasuredQuantitySchema, OBSERVATION_CONTEXT_SCHEMA_ID, ObservationAssertionSchema, ObservationContextSchema, ObservationMeasurementSchema, ObservationMethodSchema, ObservationPositionSchema, ObservationProductSchema, ObservationSnapshotRefSchema, ObservationSourceSchema, ObservationTimeSchema, PRIMITIVES_SCHEMA_ID, PositionSchema, PositionValueSchema, PrimitiveRecordSchema, ProcessingActivitySchema, QuantitativeUncertaintySchema, RESEARCH_CLAIM_HISTORY_RULESET_VERSION, RESEARCH_CLAIM_HISTORY_SCHEMA_ID, RESEARCH_ENTITIES_SCHEMA_ID, ReferenceFrameSchema, ResearchAccountFields, ResearchAssessedClaimSchema, ResearchClaimHistorySchema, ResearchClaimSubjectSchema, ResearchEntitiesSchema, ResearchEntityAssertionReferenceSchema, ResearchEntityReferenceSchema, ResearchEntitySchema, ResearchEntityTargetSchema, ResearchHistoricalClaimSchema, ResearchProcedureFields, ResearchSourceStatementSchema, ResearchUnassessedClaimSchema, ResearchWitnessFields, ResearchWitnessGroupFields, SourceProvenanceSchema, SourceStatementSchema, UnassessedClaimSchema, ValueAssertionSchema, ValueSelectionSchema, WitnessReviewSchema, compareUtcInstants, contextAssertions, contextClaimHistoryJsonSchema, experimentalClaimHistoryJsonSchema, experimentalObservationJsonSchema, observationContextJsonSchema, parseContextClaimHistory, parseExperimentalClaimHistory, parseExperimentalObservation, parseObservationContext, parsePrimitiveRecord, parseResearchClaimHistory, parseResearchEntities, primitivesJsonSchema, researchClaimHistoryJsonSchema, researchEntitiesJsonSchema, researchEntityAssertions, researchEntityContextReferences };
2046
2919
  //# sourceMappingURL=index.js.map
2047
2920
  //# sourceMappingURL=index.js.map