@kontourai/survey 1.4.0 → 1.5.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.
@@ -1,8 +1,8 @@
1
1
  import { createInterface } from "node:readline";
2
2
  import { readFile, writeFile, rename } from "node:fs/promises";
3
3
  import { resolve, dirname } from "node:path";
4
- import { buildReviewSessionEvents, currentReviewItem, deriveQueueRowStatus, nextUnresolvedItemName, replayReviewSessionEvents, reviewSessionSummary, workbenchDecisionDefinitions, } from "../review-workbench/review-workbench.js";
5
- import { createServerReviewSessionRecord, deriveServerReviewSessionApplyResult, } from "../review-workbench/server-review-session.js";
4
+ import { buildReviewSessionEvents, currentReviewItem, deriveQueueRowStatus, nextUnresolvedItemName, reviewSessionSummary, workbenchDecisionDefinitions, } from "../review-workbench/review-workbench.js";
5
+ import { createServerReviewSessionRecord, currentSessionState, deriveServerReviewSessionApplyResult, } from "../review-workbench/server-review-session.js";
6
6
  /**
7
7
  * Minimal Model Context Protocol server over stdio for review-queue inspection
8
8
  * and decision-making against a session JSON file.
@@ -42,7 +42,7 @@ async function writeSessionFileAtomic(path, content) {
42
42
  }
43
43
  // ---- Queue helpers -------------------------------------------------------
44
44
  function queueSummaryText(snapshot, events) {
45
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
45
+ const current = currentSessionState(snapshot, events);
46
46
  const summary = reviewSessionSummary(current);
47
47
  const total = current.items.length;
48
48
  const resolved = total - summary.unresolved;
@@ -66,7 +66,7 @@ function queueSummaryText(snapshot, events) {
66
66
  ].join("\n");
67
67
  }
68
68
  function itemDetailText(item, snapshot, events) {
69
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
69
+ const current = currentSessionState(snapshot, events);
70
70
  const status = deriveQueueRowStatus(item, current);
71
71
  const decision = current.decisionsByItemName[item.metadata.name];
72
72
  const note = current.notesByItemName[item.metadata.name];
@@ -112,7 +112,7 @@ function escapeHtml(text) {
112
112
  .replace(/"/g, """);
113
113
  }
114
114
  function buildReviewCardHtml(item, snapshot, events) {
115
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
115
+ const current = currentSessionState(snapshot, events);
116
116
  const summary = reviewSessionSummary(current);
117
117
  const total = current.items.length;
118
118
  const resolved = total - summary.unresolved;
@@ -293,7 +293,7 @@ async function toolQueue(options) {
293
293
  const text = queueSummaryText(snapshot, events);
294
294
  const queueData = {
295
295
  items: snapshot.items.map((item) => {
296
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
296
+ const current = currentSessionState(snapshot, events);
297
297
  return {
298
298
  name: item.metadata.name,
299
299
  target: item.spec.target,
@@ -302,14 +302,14 @@ async function toolQueue(options) {
302
302
  candidateSetStatus: item.spec.candidateSetStatus,
303
303
  };
304
304
  }),
305
- summary: reviewSessionSummary(events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot),
306
- activeItemName: (events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot).activeItemName,
305
+ summary: reviewSessionSummary(currentSessionState(snapshot, events)),
306
+ activeItemName: currentSessionState(snapshot, events).activeItemName,
307
307
  };
308
308
  const content = [
309
309
  { type: "text", text: `${text}\n\n${JSON.stringify(queueData, null, 2)}` },
310
310
  ];
311
311
  if (!options.noUi) {
312
- const activeItem = currentReviewItem(events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot);
312
+ const activeItem = currentReviewItem(currentSessionState(snapshot, events));
313
313
  content.push(buildUiResource(activeItem, snapshot, events, "queue"));
314
314
  }
315
315
  return content;
@@ -317,7 +317,7 @@ async function toolQueue(options) {
317
317
  async function toolItem(itemName, options) {
318
318
  const file = await readSessionFile(options.sessionPath);
319
319
  const { snapshot, events } = file;
320
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
320
+ const current = currentSessionState(snapshot, events);
321
321
  const item = current.items.find((i) => i.metadata.name === itemName);
322
322
  if (!item) {
323
323
  throw new DomainError(`Unknown review item: ${itemName}`);
@@ -354,7 +354,7 @@ async function toolDecide(itemName, mcpDecision, note, options) {
354
354
  }
355
355
  const file = await readSessionFile(options.sessionPath);
356
356
  const { snapshot, events } = file;
357
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
357
+ const current = currentSessionState(snapshot, events);
358
358
  const item = current.items.find((i) => i.metadata.name === itemName);
359
359
  if (!item) {
360
360
  throw new DomainError(`Unknown review item: ${itemName}`);
@@ -436,7 +436,7 @@ function buildUiResource(item, snapshot, events, instance) {
436
436
  // embedded `queue` resource carries — here served via resources/read).
437
437
  async function readQueuePanelHtml(options) {
438
438
  const { snapshot, events } = await readSessionFile(options.sessionPath);
439
- const current = events.length > 0 ? replayReviewSessionEvents(snapshot, events) : snapshot;
439
+ const current = currentSessionState(snapshot, events);
440
440
  const activeItem = currentReviewItem(current);
441
441
  return buildReviewCardHtml(activeItem, snapshot, events);
442
442
  }
@@ -1,5 +1,41 @@
1
1
  import type { SurveyObservationInput } from "./builder.js";
2
- export interface BuildObservationInput<TValue> {
2
+ /**
3
+ * Observation authoring core — CONTEXT.md "Observation" / "Field Observation
4
+ * and Repeated Observation" ("helper shapes for authoring Observations, not
5
+ * separate domain concepts").
6
+ *
7
+ * `buildObservation`/`BuildObservationInput` are the shared authoring
8
+ * primitive: they own the `extraction.target`/`value`/`excerpt` and
9
+ * `claim.fieldOrBehavior`/`value`/`metadata` assembly (including the
10
+ * three-way `claim.metadata` / caller `metadata` / representation-supplied
11
+ * `surveyMetadata` merge below). Consumed by relative import from
12
+ * `field-observation.ts`, `repeated-observation.ts` (via the
13
+ * representation-keyed `buildFieldObservation`/`buildRepeatedObservation`
14
+ * wrappers below), and `source-of-authority-observation.ts`, which calls
15
+ * `buildObservation` directly with its own `surveyMetadata`/`defaultExcerpt`.
16
+ * None of this is re-exported from `src/index.ts`.
17
+ *
18
+ * `ObservationAuthoringInput` is the shared base shape (id/field/value/
19
+ * rawSource/extraction/reviewOutcome/claim/candidate/candidateSet/metadata)
20
+ * common to `BuildObservationInput` and the two public skins' input types
21
+ * (`FieldObservationInput`, `RepeatedObservationInput`); the skins extend it
22
+ * with only their own `representation` literal.
23
+ *
24
+ * `buildFieldObservation`/`buildRepeatedObservation` are the representation-
25
+ * keyed layer above `buildObservation`: each owns the default-excerpt
26
+ * formula and the `surveyMetadata` sub-key (`field` vs `repeated`) for its
27
+ * representation. They do not change `buildObservation`'s own signature or
28
+ * body — `source-of-authority-observation.ts` depends on that staying
29
+ * exactly as-is.
30
+ *
31
+ * `mergeObservationMetadata`/`mergeNestedRecords` are exported as a
32
+ * module-internal seam (like `src/producer-discipline.ts`) purely for direct
33
+ * test import (`tests/observation-helper.test.ts`) — consumed by relative
34
+ * import only, NOT re-exported from `src/index.ts`. Their bodies, including
35
+ * the `mergeNestedRecords` nested-record-vs-scalar asymmetry and the `??`
36
+ * null/undefined coalescing, are unchanged characterization, not a defect.
37
+ */
38
+ export interface ObservationAuthoringInput<TValue> {
3
39
  id: string;
4
40
  field: string;
5
41
  value: TValue;
@@ -15,7 +51,17 @@ export interface BuildObservationInput<TValue> {
15
51
  candidate?: SurveyObservationInput["candidate"];
16
52
  candidateSet?: SurveyObservationInput["candidateSet"];
17
53
  metadata?: Record<string, unknown>;
54
+ }
55
+ export interface BuildObservationInput<TValue> extends ObservationAuthoringInput<TValue> {
18
56
  surveyMetadata: Record<string, unknown>;
19
57
  defaultExcerpt: string;
20
58
  }
21
59
  export declare function buildObservation<TValue>(input: BuildObservationInput<TValue>): SurveyObservationInput;
60
+ export declare function buildFieldObservation<TValue>(input: ObservationAuthoringInput<TValue> & {
61
+ representation?: "scalar";
62
+ }): SurveyObservationInput;
63
+ export declare function buildRepeatedObservation<TItem>(input: ObservationAuthoringInput<readonly TItem[]> & {
64
+ representation?: "aggregate-array";
65
+ }): SurveyObservationInput;
66
+ export declare function mergeObservationMetadata(claimMetadata: Record<string, unknown> | undefined, metadata: Record<string, unknown> | undefined, surveyMetadata: Record<string, unknown>): Record<string, unknown>;
67
+ export declare function mergeNestedRecords(claimSurvey: Record<string, unknown>, survey: Record<string, unknown>, surveyMetadata: Record<string, unknown>): Record<string, unknown>;
@@ -19,7 +19,46 @@ export function buildObservation(input) {
19
19
  },
20
20
  };
21
21
  }
22
- function mergeObservationMetadata(claimMetadata, metadata, surveyMetadata) {
22
+ /**
23
+ * Representation-keyed layer above `buildObservation`. Owns the
24
+ * `surveyMetadata` sub-key name, the default-`representation` literal, and
25
+ * the default-excerpt formula for the "field" (scalar) and "repeated"
26
+ * (aggregate-array) representations — the knowledge previously duplicated
27
+ * inline in `field-observation.ts`/`repeated-observation.ts`. Called only by
28
+ * the two thin public skins; `buildObservation` itself stays representation-
29
+ * agnostic.
30
+ */
31
+ function valueSummary(value) {
32
+ if (value === null || value === undefined)
33
+ return "<empty>";
34
+ return String(value);
35
+ }
36
+ export function buildFieldObservation(input) {
37
+ const representation = input.representation ?? "scalar";
38
+ return buildObservation({
39
+ ...input,
40
+ surveyMetadata: {
41
+ field: { representation },
42
+ },
43
+ defaultExcerpt: `${input.field}: ${valueSummary(input.value)}`,
44
+ });
45
+ }
46
+ export function buildRepeatedObservation(input) {
47
+ const representation = input.representation ?? "aggregate-array";
48
+ const value = [...input.value];
49
+ return buildObservation({
50
+ ...input,
51
+ value,
52
+ surveyMetadata: {
53
+ repeated: {
54
+ representation,
55
+ itemCount: value.length,
56
+ },
57
+ },
58
+ defaultExcerpt: `${input.field}: ${value.length} item(s)`,
59
+ });
60
+ }
61
+ export function mergeObservationMetadata(claimMetadata, metadata, surveyMetadata) {
23
62
  const claimSurvey = claimMetadata?.survey && isRecord(claimMetadata.survey) ? claimMetadata.survey : {};
24
63
  const survey = metadata?.survey && isRecord(metadata.survey) ? metadata.survey : {};
25
64
  return {
@@ -32,7 +71,7 @@ function mergeObservationMetadata(claimMetadata, metadata, surveyMetadata) {
32
71
  },
33
72
  };
34
73
  }
35
- function mergeNestedRecords(claimSurvey, survey, surveyMetadata) {
74
+ export function mergeNestedRecords(claimSurvey, survey, surveyMetadata) {
36
75
  const merged = {};
37
76
  const keys = new Set([
38
77
  ...Object.keys(claimSurvey),
@@ -0,0 +1,40 @@
1
+ import type { TrustStatus } from "@kontourai/surface";
2
+ /**
3
+ * Producer Discipline core — CONTEXT.md "Producer Discipline" /
4
+ * "Source-of-Authority Observation".
5
+ *
6
+ * The one piece of the review-discipline rule proven identical, field by
7
+ * field, across both existing enforcement points (2026-07 exploration):
8
+ * - src/to-surface.ts's assertProducerDiscipline (verified/assumed claims)
9
+ * - src/source-of-authority-observation.ts's assertVerifiedPosture
10
+ * (verified/assumed source-of-authority observations)
11
+ * Both require, in the same relative order, when status is "verified" or
12
+ * "assumed": (1) a review outcome exists, (2) it has a reviewer (actor),
13
+ * (3) it has a reviewedAt time — with identical error text modulo the
14
+ * subject noun ("Claim X" vs. "Source-of-authority observation X"), which
15
+ * each call site supplies.
16
+ *
17
+ * The two sites' SOURCE LOCATOR requirements are NOT identical (to-surface
18
+ * gates on rawSource.kind !== "manual-entry" regardless of status;
19
+ * source-of-authority-observation gates on status verified/assumed
20
+ * regardless of rawSource.kind, with no manual-entry exemption), and
21
+ * source-of-authority-observation has an additional sourceRef check
22
+ * to-surface does not have. Both stay call-site-local — this module does
23
+ * not decide them.
24
+ *
25
+ * Module-internal seam (like src/producer-profile.ts): consumed by
26
+ * relative import from src/to-surface.ts and
27
+ * src/source-of-authority-observation.ts, NOT re-exported from
28
+ * src/index.ts.
29
+ */
30
+ export interface ReviewOutcomePosture {
31
+ actor?: string;
32
+ reviewedAt?: string;
33
+ }
34
+ export declare function assertReviewOutcomeDiscipline(input: {
35
+ /** Message subject, e.g. `Claim ${id}` or `Source-of-authority observation ${id}` —
36
+ * each call site supplies its own noun so error text is unchanged. */
37
+ subject: string;
38
+ status: TrustStatus | undefined;
39
+ review?: ReviewOutcomePosture;
40
+ }): void;
@@ -0,0 +1,13 @@
1
+ export function assertReviewOutcomeDiscipline(input) {
2
+ if (input.status !== "verified" && input.status !== "assumed")
3
+ return;
4
+ if (!input.review) {
5
+ throw new Error(`${input.subject} cannot be ${input.status} without a review outcome`);
6
+ }
7
+ if (!input.review.actor) {
8
+ throw new Error(`${input.subject} cannot be ${input.status} without review actor authority`);
9
+ }
10
+ if (!input.review.reviewedAt) {
11
+ throw new Error(`${input.subject} cannot be ${input.status} without reviewedAt`);
12
+ }
13
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Producer Profile core — ADR 0003 §4, CONTEXT.md "Producer Profile".
3
+ *
4
+ * This module carries the shared scaffolding every Producer Profile
5
+ * (inquiry-mapping, schema-mapping, and — from Slice 4 — agent-utterance)
6
+ * needs to turn its own proposals into Survey's existing Candidate/Candidate
7
+ * Set records: a generic proposal -> Candidate Set projection grouped by
8
+ * target, the Candidate Conflict rule, and one canonical `Candidate.metadata`
9
+ * key with a typed accessor, replacing each profile's hand-rolled projection,
10
+ * conflict check, and `as`-cast metadata round-trip.
11
+ *
12
+ * This is a module-internal seam: its exports are consumed directly by
13
+ * profile modules via relative import and are NOT re-exported from
14
+ * `src/index.ts`.
15
+ *
16
+ * Hard constraint (ADR 0003 §4): this module never decides a review outcome
17
+ * or a claim status. It only shapes proposal-backed Candidate/Candidate Set
18
+ * records — every profile still routes its output through Survey's existing
19
+ * review -> claim machinery unchanged.
20
+ */
21
+ import type { Candidate, CandidateSet, CandidateSetStatus } from "./types.js";
22
+ /**
23
+ * The one canonical `Candidate.metadata` key every Producer Profile uses to
24
+ * carry its profile-specific proposal payload. Replaces the per-profile keys
25
+ * (`mappingProposal`, `schemaMappingProposal`) each profile used before
26
+ * adopting this core module.
27
+ */
28
+ export declare const PRODUCER_PROPOSAL_METADATA_KEY: "producerProposal";
29
+ /**
30
+ * One profile-adapted proposal, ready to be projected into a Candidate inside
31
+ * a shared Candidate Set.
32
+ */
33
+ export interface CandidateSetProposal<TValue = unknown, TMetadata = unknown> {
34
+ /**
35
+ * Caller-supplied, fully-formed Candidate id. Not templated by the core so
36
+ * each profile keeps its own distinct id scheme byte-for-byte.
37
+ */
38
+ candidateId: string;
39
+ /**
40
+ * Caller-supplied, fully-formed Extraction id this proposal traces back to.
41
+ * Not templated by the core for the same reason as `candidateId`.
42
+ */
43
+ extractionId: string;
44
+ /** The proposed value, copied through to the projected Candidate verbatim. */
45
+ value: TValue;
46
+ /** Optional proposer confidence, copied through to the projected Candidate. */
47
+ confidence?: number;
48
+ /**
49
+ * The Candidate Conflict comparison key. Required, and deliberately not
50
+ * derived from `value` by the core, so each profile controls exactly what
51
+ * "agrees" means for its own domain (e.g. a compound value may still be
52
+ * considered equivalent under a narrower key than a full deep-compare).
53
+ */
54
+ equivalenceKey: string;
55
+ /**
56
+ * The profile's own payload, stored verbatim under
57
+ * {@link PRODUCER_PROPOSAL_METADATA_KEY} on the projected Candidate's
58
+ * `metadata`.
59
+ */
60
+ metadata: TMetadata;
61
+ }
62
+ /**
63
+ * The shared Candidate Conflict rule: a group of proposals conflicts iff it
64
+ * carries more than one distinct `equivalenceKey`. A group of 0 or 1
65
+ * proposals can never conflict.
66
+ */
67
+ export declare function hasCandidateConflict(proposals: Array<Pick<CandidateSetProposal, "equivalenceKey">>): boolean;
68
+ export interface ProjectProposalsToCandidateSetOptions {
69
+ /** The id for the projected Candidate Set. */
70
+ candidateSetId: string;
71
+ /** Optional metadata to attach to the projected Candidate Set. */
72
+ candidateSetMetadata?: Record<string, unknown>;
73
+ /**
74
+ * Optional rationale-builder for the projected Candidate Set, given the
75
+ * computed status and the input proposals.
76
+ */
77
+ candidateSetRationale?: (status: CandidateSetStatus, proposals: CandidateSetProposal[]) => string | undefined;
78
+ }
79
+ /**
80
+ * Build one Candidate Set (and its Candidates) from one target's proposal
81
+ * group. Grouping proposals by target itself stays a caller concern — this
82
+ * function projects exactly one group per call; it never reaches across
83
+ * multiple targets on its own. `status` is `"conflict"` when
84
+ * {@link hasCandidateConflict} is true for `proposals`, otherwise
85
+ * `"needs-review"` (an empty `proposals` array yields `"needs-review"` with
86
+ * an empty `candidates` array). `selectedCandidateId` is left unset — both
87
+ * profiles compute it themselves, or not at all, per their own review flow.
88
+ */
89
+ export declare function projectProposalsToCandidateSet<TValue = unknown, TMetadata = unknown>(target: string, proposals: Array<CandidateSetProposal<TValue, TMetadata>>, options: ProjectProposalsToCandidateSetOptions): {
90
+ candidateSet: CandidateSet;
91
+ candidates: Candidate[];
92
+ };
93
+ /**
94
+ * Typed read-back of the proposal payload a Candidate carries under
95
+ * {@link PRODUCER_PROPOSAL_METADATA_KEY}. Returns `undefined` if the
96
+ * Candidate, its `metadata`, or the key itself is absent — never throws.
97
+ *
98
+ * No fallback reads of any legacy per-profile metadata key are performed
99
+ * (Owner decision: no legacy support).
100
+ */
101
+ export declare function getProducerProposal<TMetadata>(candidate: Candidate | undefined): TMetadata | undefined;
102
+ /**
103
+ * Actor identity every Producer Profile's auto-accept policy uses when it
104
+ * accepts a proposal without human review. Shared literal — see ADR 0003
105
+ * §4 (the core never decides "verified"; auto-accept only ever produces
106
+ * "assumed" + comfort-zone true).
107
+ */
108
+ export declare const AUTO_ACCEPT_ACTOR: "auto-accept-policy";
109
+ /**
110
+ * The comfort-zone posture every Producer Profile's auto-accept policy
111
+ * sets when it accepts a proposal: `withinComfortZone: true` always — an
112
+ * auto-accepted proposal is, by definition, one the policy's declared
113
+ * threshold covers, so there is nothing "outside comfort zone" about an
114
+ * auto-accept decision (ADR 0003 §4).
115
+ */
116
+ export declare const AUTO_ACCEPT_WITHIN_COMFORT_ZONE: true;
117
+ /**
118
+ * The one auto-accept threshold rule every Producer Profile applies: a
119
+ * confidence value clears an auto-accept policy iff it is at or above
120
+ * (inclusive) the policy's minimum confidence. This is the only piece of
121
+ * auto-accept *mechanics* that is identical across profiles today — each
122
+ * profile decides its own iteration granularity (per-proposal filter vs.
123
+ * per-group max-confidence gate) and output record shape around this call;
124
+ * the core does not decide that.
125
+ *
126
+ * These three exports are the ONLY auto-accept semantics the two profiles
127
+ * genuinely share today (see the Slice 3 plan's Part (a) field-by-field
128
+ * diff table). Everything else about auto-accept — iteration granularity
129
+ * (per-proposal vs. per-group), output record type and cardinality, id
130
+ * templates, timestamp source, and rationale string format — diverges
131
+ * between profiles and stays entirely per-profile; this module does not
132
+ * decide any of it.
133
+ */
134
+ export declare function meetsAutoAcceptThreshold(confidence: number, minConfidence: number): boolean;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Producer Profile core — ADR 0003 §4, CONTEXT.md "Producer Profile".
3
+ *
4
+ * This module carries the shared scaffolding every Producer Profile
5
+ * (inquiry-mapping, schema-mapping, and — from Slice 4 — agent-utterance)
6
+ * needs to turn its own proposals into Survey's existing Candidate/Candidate
7
+ * Set records: a generic proposal -> Candidate Set projection grouped by
8
+ * target, the Candidate Conflict rule, and one canonical `Candidate.metadata`
9
+ * key with a typed accessor, replacing each profile's hand-rolled projection,
10
+ * conflict check, and `as`-cast metadata round-trip.
11
+ *
12
+ * This is a module-internal seam: its exports are consumed directly by
13
+ * profile modules via relative import and are NOT re-exported from
14
+ * `src/index.ts`.
15
+ *
16
+ * Hard constraint (ADR 0003 §4): this module never decides a review outcome
17
+ * or a claim status. It only shapes proposal-backed Candidate/Candidate Set
18
+ * records — every profile still routes its output through Survey's existing
19
+ * review -> claim machinery unchanged.
20
+ */
21
+ // ---------------------------------------------------------------------------
22
+ // Canonical proposal-metadata key
23
+ // ---------------------------------------------------------------------------
24
+ /**
25
+ * The one canonical `Candidate.metadata` key every Producer Profile uses to
26
+ * carry its profile-specific proposal payload. Replaces the per-profile keys
27
+ * (`mappingProposal`, `schemaMappingProposal`) each profile used before
28
+ * adopting this core module.
29
+ */
30
+ export const PRODUCER_PROPOSAL_METADATA_KEY = "producerProposal";
31
+ // ---------------------------------------------------------------------------
32
+ // Candidate Conflict rule
33
+ // ---------------------------------------------------------------------------
34
+ /**
35
+ * The shared Candidate Conflict rule: a group of proposals conflicts iff it
36
+ * carries more than one distinct `equivalenceKey`. A group of 0 or 1
37
+ * proposals can never conflict.
38
+ */
39
+ export function hasCandidateConflict(proposals) {
40
+ return new Set(proposals.map((p) => p.equivalenceKey)).size > 1;
41
+ }
42
+ /**
43
+ * Build one Candidate Set (and its Candidates) from one target's proposal
44
+ * group. Grouping proposals by target itself stays a caller concern — this
45
+ * function projects exactly one group per call; it never reaches across
46
+ * multiple targets on its own. `status` is `"conflict"` when
47
+ * {@link hasCandidateConflict} is true for `proposals`, otherwise
48
+ * `"needs-review"` (an empty `proposals` array yields `"needs-review"` with
49
+ * an empty `candidates` array). `selectedCandidateId` is left unset — both
50
+ * profiles compute it themselves, or not at all, per their own review flow.
51
+ */
52
+ export function projectProposalsToCandidateSet(target, proposals, options) {
53
+ const candidates = proposals.map((proposal) => ({
54
+ id: proposal.candidateId,
55
+ extractionId: proposal.extractionId,
56
+ value: proposal.value,
57
+ confidence: proposal.confidence,
58
+ metadata: {
59
+ [PRODUCER_PROPOSAL_METADATA_KEY]: proposal.metadata,
60
+ },
61
+ }));
62
+ const status = hasCandidateConflict(proposals) ? "conflict" : "needs-review";
63
+ const candidateSet = {
64
+ id: options.candidateSetId,
65
+ target,
66
+ candidates,
67
+ status,
68
+ rationale: options.candidateSetRationale?.(status, proposals),
69
+ metadata: options.candidateSetMetadata,
70
+ };
71
+ return { candidateSet, candidates };
72
+ }
73
+ // ---------------------------------------------------------------------------
74
+ // Typed proposal-metadata accessor
75
+ // ---------------------------------------------------------------------------
76
+ /**
77
+ * Typed read-back of the proposal payload a Candidate carries under
78
+ * {@link PRODUCER_PROPOSAL_METADATA_KEY}. Returns `undefined` if the
79
+ * Candidate, its `metadata`, or the key itself is absent — never throws.
80
+ *
81
+ * No fallback reads of any legacy per-profile metadata key are performed
82
+ * (Owner decision: no legacy support).
83
+ */
84
+ export function getProducerProposal(candidate) {
85
+ return candidate?.metadata?.[PRODUCER_PROPOSAL_METADATA_KEY];
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // Shared auto-accept primitives
89
+ // ---------------------------------------------------------------------------
90
+ /**
91
+ * Actor identity every Producer Profile's auto-accept policy uses when it
92
+ * accepts a proposal without human review. Shared literal — see ADR 0003
93
+ * §4 (the core never decides "verified"; auto-accept only ever produces
94
+ * "assumed" + comfort-zone true).
95
+ */
96
+ export const AUTO_ACCEPT_ACTOR = "auto-accept-policy";
97
+ /**
98
+ * The comfort-zone posture every Producer Profile's auto-accept policy
99
+ * sets when it accepts a proposal: `withinComfortZone: true` always — an
100
+ * auto-accepted proposal is, by definition, one the policy's declared
101
+ * threshold covers, so there is nothing "outside comfort zone" about an
102
+ * auto-accept decision (ADR 0003 §4).
103
+ */
104
+ export const AUTO_ACCEPT_WITHIN_COMFORT_ZONE = true;
105
+ /**
106
+ * The one auto-accept threshold rule every Producer Profile applies: a
107
+ * confidence value clears an auto-accept policy iff it is at or above
108
+ * (inclusive) the policy's minimum confidence. This is the only piece of
109
+ * auto-accept *mechanics* that is identical across profiles today — each
110
+ * profile decides its own iteration granularity (per-proposal filter vs.
111
+ * per-group max-confidence gate) and output record shape around this call;
112
+ * the core does not decide that.
113
+ *
114
+ * These three exports are the ONLY auto-accept semantics the two profiles
115
+ * genuinely share today (see the Slice 3 plan's Part (a) field-by-field
116
+ * diff table). Everything else about auto-accept — iteration granularity
117
+ * (per-proposal vs. per-group), output record type and cardinality, id
118
+ * templates, timestamp source, and rationale string format — diverges
119
+ * between profiles and stays entirely per-profile; this module does not
120
+ * decide any of it.
121
+ */
122
+ export function meetsAutoAcceptThreshold(confidence, minConfidence) {
123
+ return confidence >= minConfidence;
124
+ }
@@ -39,6 +39,24 @@ export interface PolicyStandardSourceInput extends Omit<RawSourceInput, "locator
39
39
  locatorScheme?: LocatorScheme;
40
40
  metadata?: Record<string, unknown>;
41
41
  }
42
+ /**
43
+ * Raw Source kinds whose factories accept a caller-supplied `locatorScheme`
44
+ * override and otherwise fall back to a per-kind default. `uploaded-document`
45
+ * has no default (`undefined`) because `UploadedDocumentSourceInput.locatorScheme`
46
+ * is required, not optional — modeled here as a real, explicit table entry
47
+ * rather than an omission, so a caller-supplied value is the only source of
48
+ * truth for that kind.
49
+ *
50
+ * Module-internal seam: consumed by relative import from
51
+ * `rawSourceWithDefaultLocatorScheme` below and by
52
+ * `tests/raw-source-defaults.test.ts`, NOT re-exported from `src/index.ts`.
53
+ */
54
+ export declare const DEFAULT_LOCATOR_SCHEME: {
55
+ "uploaded-document": undefined;
56
+ "api-record": LocatorScheme;
57
+ "web-page": LocatorScheme;
58
+ "manual-entry": LocatorScheme;
59
+ };
42
60
  export declare function uploadedDocumentSource(input: UploadedDocumentSourceInput): RawSource;
43
61
  export declare function apiRecordSource(input: ApiRecordSourceInput): RawSource;
44
62
  export declare function webPageSource(input: WebPageSourceInput): RawSource;
@@ -1,23 +1,38 @@
1
+ /**
2
+ * Raw Source kinds whose factories accept a caller-supplied `locatorScheme`
3
+ * override and otherwise fall back to a per-kind default. `uploaded-document`
4
+ * has no default (`undefined`) because `UploadedDocumentSourceInput.locatorScheme`
5
+ * is required, not optional — modeled here as a real, explicit table entry
6
+ * rather than an omission, so a caller-supplied value is the only source of
7
+ * truth for that kind.
8
+ *
9
+ * Module-internal seam: consumed by relative import from
10
+ * `rawSourceWithDefaultLocatorScheme` below and by
11
+ * `tests/raw-source-defaults.test.ts`, NOT re-exported from `src/index.ts`.
12
+ */
13
+ export const DEFAULT_LOCATOR_SCHEME = {
14
+ "uploaded-document": undefined,
15
+ "api-record": "structured-field",
16
+ "web-page": "html",
17
+ "manual-entry": "structured-field",
18
+ };
19
+ function rawSourceWithDefaultLocatorScheme(kind, input) {
20
+ return rawSource(kind, {
21
+ locatorScheme: DEFAULT_LOCATOR_SCHEME[kind],
22
+ ...input,
23
+ });
24
+ }
1
25
  export function uploadedDocumentSource(input) {
2
- return rawSource("uploaded-document", input);
26
+ return rawSourceWithDefaultLocatorScheme("uploaded-document", input);
3
27
  }
4
28
  export function apiRecordSource(input) {
5
- return rawSource("api-record", {
6
- locatorScheme: "structured-field",
7
- ...input,
8
- });
29
+ return rawSourceWithDefaultLocatorScheme("api-record", input);
9
30
  }
10
31
  export function webPageSource(input) {
11
- return rawSource("web-page", {
12
- locatorScheme: "html",
13
- ...input,
14
- });
32
+ return rawSourceWithDefaultLocatorScheme("web-page", input);
15
33
  }
16
34
  export function manualEntrySource(input) {
17
- return rawSource("manual-entry", {
18
- locatorScheme: "structured-field",
19
- ...input,
20
- });
35
+ return rawSourceWithDefaultLocatorScheme("manual-entry", input);
21
36
  }
22
37
  export function policyStandardSource(input) {
23
38
  const policyStandard = {
@@ -1,20 +1,6 @@
1
1
  import type { SurveyObservationInput } from "./builder.js";
2
- export interface RepeatedObservationInput<TItem> {
3
- id: string;
4
- field: string;
5
- value: readonly TItem[];
6
- rawSource: SurveyObservationInput["rawSource"];
7
- extraction: Omit<SurveyObservationInput["extraction"], "target" | "value" | "excerpt"> & {
8
- target?: string;
9
- excerpt?: string | null;
10
- };
11
- reviewOutcome?: SurveyObservationInput["reviewOutcome"];
12
- claim: Omit<SurveyObservationInput["claim"], "fieldOrBehavior" | "value"> & {
13
- fieldOrBehavior?: string;
14
- };
15
- candidate?: SurveyObservationInput["candidate"];
16
- candidateSet?: SurveyObservationInput["candidateSet"];
2
+ import { type ObservationAuthoringInput } from "./observation-helper.js";
3
+ export interface RepeatedObservationInput<TItem> extends ObservationAuthoringInput<readonly TItem[]> {
17
4
  representation?: "aggregate-array";
18
- metadata?: Record<string, unknown>;
19
5
  }
20
6
  export declare function repeatedObservation<TItem>(input: RepeatedObservationInput<TItem>): SurveyObservationInput;
@@ -1,16 +1,4 @@
1
- import { buildObservation } from "./observation-helper.js";
1
+ import { buildRepeatedObservation } from "./observation-helper.js";
2
2
  export function repeatedObservation(input) {
3
- const representation = input.representation ?? "aggregate-array";
4
- const value = [...input.value];
5
- return buildObservation({
6
- ...input,
7
- value,
8
- surveyMetadata: {
9
- repeated: {
10
- representation,
11
- itemCount: value.length,
12
- },
13
- },
14
- defaultExcerpt: `${input.field}: ${value.length} item(s)`,
15
- });
3
+ return buildRepeatedObservation(input);
16
4
  }