@kontourai/survey 7.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +2 -1
  3. package/dist/src/calibration.d.ts +15 -0
  4. package/dist/src/calibration.js +11 -0
  5. package/dist/src/canonical-reviewed-trust-input.d.ts +10 -0
  6. package/dist/src/canonical-reviewed-trust-input.js +15 -0
  7. package/dist/src/console/review-console-server.d.ts +20 -0
  8. package/dist/src/console/review-console-server.js +75 -4
  9. package/dist/src/decision-carry-forward.d.ts +157 -0
  10. package/dist/src/decision-carry-forward.js +295 -0
  11. package/dist/src/extraction-envelope.d.ts +4 -3
  12. package/dist/src/extraction-envelope.js +3 -3
  13. package/dist/src/field-states.d.ts +100 -0
  14. package/dist/src/field-states.js +169 -0
  15. package/dist/src/index.d.ts +3 -1
  16. package/dist/src/index.js +2 -0
  17. package/dist/src/mcp/review-mcp.js +44 -13
  18. package/dist/src/review-resource.d.ts +29 -0
  19. package/dist/src/review-session-file.d.ts +6 -0
  20. package/dist/src/review-session-file.js +2 -0
  21. package/dist/src/review-workbench/audit-sample.d.ts +32 -0
  22. package/dist/src/review-workbench/audit-sample.js +53 -0
  23. package/dist/src/review-workbench/extraction-inspector.d.ts +1 -1
  24. package/dist/src/review-workbench/extraction-inspector.js +1 -1
  25. package/dist/src/review-workbench/field-state-view.d.ts +15 -0
  26. package/dist/src/review-workbench/field-state-view.js +84 -0
  27. package/dist/src/review-workbench/review-queue-session.d.ts +46 -1
  28. package/dist/src/review-workbench/review-queue-session.js +74 -3
  29. package/dist/src/review-workbench/review-session-replay.d.ts +1 -1
  30. package/dist/src/review-workbench/review-session-replay.js +15 -1
  31. package/dist/src/review-workbench/review-workbench-css.generated.d.ts +9 -0
  32. package/dist/src/review-workbench/review-workbench-css.generated.js +453 -43
  33. package/dist/src/review-workbench/review-workbench-element.js +68 -212
  34. package/dist/src/review-workbench/review-workbench.css +386 -42
  35. package/dist/src/review-workbench/review-workbench.d.ts +13 -1
  36. package/dist/src/review-workbench/review-workbench.js +41 -15
  37. package/dist/src/review-workbench/review-workbench.standalone.css +37 -23
  38. package/dist/src/review-workbench/vendor/kontourai-ui/tokens/themes.css +189 -10
  39. package/dist/src/review-workbench/vendor/kontourai-ui/tokens/tokens.css +156 -5
  40. package/package.json +13 -8
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/%40kontourai%2Fsurvey)](https://www.npmjs.com/package/@kontourai/survey)
8
8
  [![CI](https://github.com/kontourai/survey/actions/workflows/ci.yml/badge.svg)](https://github.com/kontourai/survey/actions/workflows/ci.yml)
9
+ [![Docs](https://img.shields.io/badge/docs-kontourai.github.io-blue)](https://kontourai.github.io/survey/)
9
10
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
10
11
 
11
12
  [Documentation](https://kontourai.github.io/survey/) · [Record Contracts](docs/record-contracts.md) · [Consumer Guide](docs/consumer-integration-guide.md) · [kontourai.io/survey](https://kontourai.io/survey)
@@ -30,7 +31,7 @@ Survey does not decide whether a real-world value is true. It preserves the prod
30
31
 
31
32
  ## See it
32
33
 
33
- The Review Workbench rendering a real example queue — current vs proposed values, source evidence, decision effect, and the Surface projection preview:
34
+ The Review Workbench rendering a real example queue — current vs proposed values, source evidence, decision effect, and the Surface projection preview. [Open the live demo](https://kontourai.github.io/survey/demo/).
34
35
 
35
36
  ![Survey Review Workbench showing a review queue, current versus proposed values, decision controls, and a Surface preview](docs/assets/review-workbench-desktop.png)
36
37
 
@@ -75,6 +75,21 @@ export interface DeriveCalibrationOptions {
75
75
  * labeled samples. Default false — see the module note on circularity.
76
76
  */
77
77
  readonly includeAutoAccepted?: boolean;
78
+ /**
79
+ * Count only audit labels: outcomes whose metadata records a score-blind
80
+ * decision (`presentation.scoreBlind === true`) on a random audit sample
81
+ * (`sampling.kind === "random-audit"`), as the review workbench writes them
82
+ * for a session opened with `openRandomAuditSession`. Default false (every
83
+ * human outcome counts, as before). Other outcomes are skipped and counted
84
+ * in `skippedCount`, as windowed-out outcomes are.
85
+ *
86
+ * Calibration reads these fields as recorded on the outcome. The review
87
+ * session validates them (a `random-audit` rate in (0, 1] and a stable seed)
88
+ * and replay refuses events recorded under other conditions than the
89
+ * snapshot's, but an outcome assembled outside Survey's apply path is taken
90
+ * at its word: only feed outcomes from a store you trust.
91
+ */
92
+ readonly auditSamplesOnly?: boolean;
78
93
  }
79
94
  /** One labeled calibration sample: a prediction paired with the human label. */
80
95
  export interface CalibrationSample {
@@ -80,6 +80,10 @@ export function deriveCalibration(input, options = {}) {
80
80
  const samples = [];
81
81
  let skippedCount = 0;
82
82
  for (const outcome of input.reviewOutcomes) {
83
+ if (options.auditSamplesOnly && !isScoreBlindAuditOutcome(outcome)) {
84
+ skippedCount++;
85
+ continue;
86
+ }
83
87
  if (outcome.resolution === "could_not_confirm") {
84
88
  skippedCount++;
85
89
  continue;
@@ -142,6 +146,13 @@ export function deriveCalibration(input, options = {}) {
142
146
  // ---------------------------------------------------------------------------
143
147
  // Internal: sample construction
144
148
  // ---------------------------------------------------------------------------
149
+ /** A decision recorded score-blind on a random audit sample (see `openRandomAuditSession`). */
150
+ function isScoreBlindAuditOutcome(outcome) {
151
+ const presentation = outcome.metadata?.presentation;
152
+ const sampling = outcome.metadata?.sampling;
153
+ return typeof presentation === "object" && presentation !== null && presentation.scoreBlind === true
154
+ && typeof sampling === "object" && sampling !== null && sampling.kind === "random-audit";
155
+ }
145
156
  function toSample(outcome, candidateSetById, extractionById, includeAutoAccepted) {
146
157
  // No human label yet.
147
158
  if (outcome.status === "proposed")
@@ -1,6 +1,7 @@
1
1
  import type { SurveyInput } from "./types.js";
2
2
  import type { ReviewItem } from "./review-resource.js";
3
3
  import type { ReviewWorkbenchResult } from "./review-workbench/review-workbench.js";
4
+ import { type DeriveFieldStatesInput } from "./field-states.js";
4
5
  export interface BuildCanonicalReviewedTrustInputOptions {
5
6
  /** Producer identity for the resulting SurveyInput batch. */
6
7
  readonly source: string;
@@ -12,6 +13,15 @@ export interface BuildCanonicalReviewedTrustInputOptions {
12
13
  readonly items: readonly ReviewItem[];
13
14
  /** Results derived by Survey's server apply boundary from snapshot + events. */
14
15
  readonly results: readonly ReviewWorkbenchResult[];
16
+ /**
17
+ * The extraction imports the items came from (and optionally verifier
18
+ * records and supersessions). When present, each claim whose item one of
19
+ * these imports produced carries its derived content and lifecycle states
20
+ * under `metadata["survey.kontourai.io/field-state"]` (see
21
+ * `deriveFieldStates`). The states are derived here from the imports and the
22
+ * results' own decisions, never supplied as labels. Claim status is unchanged.
23
+ */
24
+ readonly fieldStates?: Omit<DeriveFieldStatesInput, "decisions" | "carryForwards">;
15
25
  }
16
26
  export interface CanonicalReviewedTrustInput {
17
27
  readonly surveyInput: SurveyInput;
@@ -1,6 +1,7 @@
1
1
  import { SURVEY_INPUT_CONTRACT_VERSION } from "./types.js";
2
2
  import { canonicalJson } from "./review-workbench/canonical.js";
3
3
  import { decisionSelectsNoCandidate, workbenchDecisionDefinitions } from "./review-workbench/review-queue-session.js";
4
+ import { deriveFieldStates, fieldStateClaimMetadata, FIELD_STATE_METADATA_KEY } from "./field-states.js";
4
5
  /**
5
6
  * Projects server-applied review records into the complete SurveyInput consumed
6
7
  * by buildSurveyTrustBundle. The ReviewItem and ReviewWorkbenchResult are the
@@ -22,6 +23,13 @@ export function buildCanonicalReviewedTrustInput(options) {
22
23
  if (itemsByName.size !== resultsByName.size) {
23
24
  throw new Error("Canonical review projection requires exactly one resolved result for every ReviewItem.");
24
25
  }
26
+ const fieldStatesByItem = new Map();
27
+ if (options.fieldStates) {
28
+ const states = deriveFieldStates({ ...options.fieldStates, decisions: options.results.map((result) => result.reviewDecision) });
29
+ for (const state of states)
30
+ if (state.reviewItemName !== undefined)
31
+ fieldStatesByItem.set(state.reviewItemName, state);
32
+ }
25
33
  const rawSources = new Map();
26
34
  const extractions = new Map();
27
35
  const candidateSets = new Map();
@@ -106,6 +114,10 @@ export function buildCanonicalReviewedTrustInput(options) {
106
114
  ...(decision.unselectedCandidateIds?.length
107
115
  ? { unselectedCandidateIds: decision.unselectedCandidateIds.map((id) => recordIdFor(item, id)) }
108
116
  : {}),
117
+ // How the decision was made: whether scores were hidden, and how the
118
+ // item was sampled. Calibration reads these to select audit labels.
119
+ ...(decision.presentation !== undefined ? { presentation: { scoreBlind: decision.presentation.scoreBlind } } : {}),
120
+ ...(decision.sampling !== undefined ? { sampling: { ...decision.sampling } } : {}),
109
121
  },
110
122
  };
111
123
  addConsistent(reviewOutcomes, reviewOutcome, "review outcome");
@@ -146,6 +158,9 @@ export function buildCanonicalReviewedTrustInput(options) {
146
158
  ...(hint.derivedFrom ? { derivedFrom: [...hint.derivedFrom] } : {}),
147
159
  collectedBy: hint.collectedBy ?? sharedExtractor(selected ? [selected] : item.spec.candidates) ?? options.source,
148
160
  ...(decision.actor?.id ? { actor: decision.actor.id } : {}),
161
+ ...(fieldStatesByItem.has(item.metadata.name)
162
+ ? { metadata: { [FIELD_STATE_METADATA_KEY]: fieldStateClaimMetadata(fieldStatesByItem.get(item.metadata.name)) } }
163
+ : {}),
149
164
  };
150
165
  addConsistent(claims, claim, "claim target");
151
166
  }
@@ -12,6 +12,10 @@
12
12
  * GET /api/health Health check
13
13
  * GET /dist/* Compiled assets served from the dist tree (traversal-safe)
14
14
  */
15
+ import { type ServerReviewSessionRecord } from "../review-workbench/server-review-session.js";
16
+ import { type ReviewQueueBinding } from "../review-workbench/queue-binding.js";
17
+ import type { ReviewWorkbenchResult } from "../review-workbench/review-workbench.js";
18
+ import type { ReviewSessionEvent } from "../review-resource.js";
15
19
  export interface ReviewConsoleServerOptions {
16
20
  /** Absolute path to the session JSON file. */
17
21
  readonly sessionPath: string;
@@ -19,6 +23,22 @@ export interface ReviewConsoleServerOptions {
19
23
  readonly port?: number;
20
24
  /** Host to bind on. Must be a loopback address. Defaults to 127.0.0.1. */
21
25
  readonly host?: string;
26
+ /** Producer-owned application. The binding must come from queue construction. */
27
+ readonly producerApply?: {
28
+ readonly binding: ReviewQueueBinding;
29
+ /** Revalidate domain currency/authentication and apply idempotently under the producer's lock. */
30
+ readonly apply: (input: ReviewConsoleApplyInput) => Promise<ReviewConsoleApplication>;
31
+ };
32
+ }
33
+ export interface ReviewConsoleApplyInput {
34
+ readonly record: ServerReviewSessionRecord;
35
+ readonly events: readonly ReviewSessionEvent[];
36
+ readonly results: readonly ReviewWorkbenchResult[];
37
+ readonly revision: string;
38
+ }
39
+ export interface ReviewConsoleApplication {
40
+ readonly reference: string;
41
+ readonly summary: string;
22
42
  }
23
43
  export interface ReviewConsoleServerHandle {
24
44
  readonly url: string;
@@ -163,7 +163,7 @@ async function serveDistFile(distDir, pathname, res) {
163
163
  // ---------------------------------------------------------------------------
164
164
  // HTML shell
165
165
  // ---------------------------------------------------------------------------
166
- function buildConsoleHtml(sessionPath) {
166
+ function buildConsoleHtml(sessionPath, canApply) {
167
167
  const escapedPath = sessionPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'");
168
168
  // workbench.js lives at dist/src/review-workbench/review-workbench.js relative to distRoot
169
169
  const workbenchJsPath = "/dist/src/review-workbench/review-workbench.js";
@@ -253,7 +253,7 @@ body {
253
253
  gap: 5px;
254
254
  font-family: var(--k-font-mono, monospace);
255
255
  font-size: 10px;
256
- color: var(--k-text-faint, #72869b);
256
+ color: var(--k-text-faint, #75889d);
257
257
  padding: 3px 8px;
258
258
  border: 1px solid var(--k-line, rgba(150,180,210,0.12));
259
259
  border-radius: 999px;
@@ -314,6 +314,7 @@ body {
314
314
  </button>
315
315
  </div>
316
316
  </header>
317
+ ${canApply ? '<div style="display:flex;justify-content:flex-end;padding:8px 16px"><button type="button" id="apply-review" class="theme-toggle">Send review to workflow</button></div>' : ''}
317
318
  <div id="console-save-status" class="console-save-status" role="alert" data-testid="console-save-status" hidden></div>
318
319
  <main id="review-workbench" class="workbench survey-workbench-embed" data-testid="review-workbench"></main>
319
320
  <script type="module">
@@ -376,7 +377,7 @@ function createConsoleEventStore(baseRevision) {
376
377
  }
377
378
  if (res.ok) {
378
379
  const body = await res.json().catch(() => ({}));
379
- if (typeof body.revision === "string") revision = body.revision;
380
+ if (typeof body.revision === "string") { revision = body.revision; currentRevision = revision; }
380
381
  persistedCount = localEvents.length;
381
382
  showSaveStatus("");
382
383
  return;
@@ -395,12 +396,34 @@ function createConsoleEventStore(baseRevision) {
395
396
  save: (_session, events) => {
396
397
  const localEvents = [...events];
397
398
  saveChain = saveChain.then(() => persist(localEvents));
399
+ pendingSave = saveChain;
398
400
  return saveChain;
399
401
  },
400
402
  };
401
403
  }
402
404
 
403
405
  let activeItemName = null;
406
+ let currentRevision = null;
407
+ let applying = false;
408
+ let wasApplied = false;
409
+ let pendingSave = Promise.resolve();
410
+ const applyButton = document.getElementById("apply-review");
411
+ applyButton?.addEventListener("click", async () => {
412
+ if (applying || !currentRevision) return;
413
+ applying = true;
414
+ applyButton.disabled = true;
415
+ try {
416
+ await pendingSave;
417
+ const response = await fetch("/api/apply", {
418
+ method: "POST", headers: { "Content-Type": "application/json" },
419
+ body: JSON.stringify({ baseRevision: currentRevision }),
420
+ });
421
+ const body = await response.json();
422
+ showSaveStatus(response.ok ? body.application.summary : body.error);
423
+ await fetchAndMount();
424
+ } catch { showSaveStatus("The review could not reach the workflow. Reload before trying again."); }
425
+ finally { applying = false; applyButton.disabled = wasApplied || !currentRevision; }
426
+ });
404
427
 
405
428
  async function fetchAndMount() {
406
429
  try {
@@ -414,6 +437,9 @@ async function fetchAndMount() {
414
437
  }
415
438
  const data = await res.json();
416
439
  const { snapshot, events, revision, extractionImport } = data;
440
+ currentRevision = revision;
441
+ wasApplied = Boolean(data.producerApplication);
442
+ if (applyButton) applyButton.disabled = applying || wasApplied;
417
443
  const state = events && events.length > 0
418
444
  ? replayReviewSessionEvents(snapshot, events)
419
445
  : snapshot;
@@ -574,6 +600,10 @@ export async function startReviewConsoleServer(options) {
574
600
  throw new Error("survey-review-console only serves loopback addresses");
575
601
  }
576
602
  const sessionPath = resolve(options.sessionPath);
603
+ const producerApply = options.producerApply ? {
604
+ binding: structuredClone(options.producerApply.binding),
605
+ apply: options.producerApply.apply,
606
+ } : undefined;
577
607
  const distDir = distRoot();
578
608
  const broadcaster = createSseBroadcaster();
579
609
  const stopWatcher = watchSessionFile(sessionPath, () => {
@@ -624,6 +654,7 @@ export async function startReviewConsoleServer(options) {
624
654
  revision: reviewSessionRevision(content.events),
625
655
  state: currentSessionState(content.snapshot, content.events),
626
656
  queueAttestation: attestation.state,
657
+ ...(content.producerApplication ? { producerApplication: content.producerApplication } : {}),
627
658
  ...(content.extractionImport !== undefined ? { extractionImport: content.extractionImport } : {}),
628
659
  });
629
660
  return;
@@ -650,6 +681,8 @@ export async function startReviewConsoleServer(options) {
650
681
  const outcome = await updateReviewSessionFile(sessionPath, (content) => {
651
682
  const { snapshot, events: existingEvents } = content;
652
683
  const revision = reviewSessionRevision(existingEvents);
684
+ if (content.producerApplication !== undefined)
685
+ return { result: { status: 409, body: { error: "This review was sent to its workflow; open a new review session", revision } } };
653
686
  // Compare-and-swap: the appended events express decisions made on
654
687
  // the reviewer's view of the log, so they are only safe to append
655
688
  // when that view is the log that is stored right now.
@@ -700,6 +733,44 @@ export async function startReviewConsoleServer(options) {
700
733
  sendJson(res, outcome.status, outcome.body);
701
734
  return;
702
735
  }
736
+ // ---- Producer-owned workflow application ----
737
+ if (pathname === "/api/apply" && req.method === "POST") {
738
+ if (!producerApply) {
739
+ sendJson(res, 404, { error: "No workflow application is configured" });
740
+ return;
741
+ }
742
+ const guardError = originGuard(req, listenPort) ?? contentTypeGuard(req);
743
+ if (guardError) {
744
+ sendJson(res, 403, { error: guardError });
745
+ return;
746
+ }
747
+ const body = await readJsonBody(req);
748
+ const outcome = await updateReviewSessionFile(sessionPath, async (content) => {
749
+ const revision = reviewSessionRevision(content.events);
750
+ if (typeof body.baseRevision !== "string")
751
+ return { result: { status: 428, body: { error: "baseRevision is required" } } };
752
+ if (body.baseRevision !== revision)
753
+ return { result: { status: 409, body: { error: "Session changed since it was read; reload before sending it" } } };
754
+ if (content.producerApplication !== undefined)
755
+ return { result: { status: 409, body: { error: "This review was already sent to its workflow" } } };
756
+ const record = createServerReviewSessionRecord({ sessionName: storedReviewSessionName(content), snapshot: content.snapshot, eventCount: content.events.length });
757
+ try {
758
+ const derived = deriveServerReviewSessionApplyResult({ record, events: content.events, binding: producerApply.binding, extractionImport: content.extractionImport, requiredResolvedItems: "all" });
759
+ if (!derived.ok)
760
+ return { result: { status: 422, body: { error: "Resolve every review item before sending it to the workflow" } } };
761
+ const application = await producerApply.apply(structuredClone({ record, events: content.events, results: derived.results, revision }));
762
+ if (!application || typeof application.reference !== "string" || !application.reference.trim() || application.reference.length > 2048 || typeof application.summary !== "string" || !application.summary.trim() || application.summary.length > 4096)
763
+ throw new Error("Workflow returned an invalid application receipt");
764
+ const stored = { reference: application.reference, summary: application.summary, revision };
765
+ return { next: { ...content, producerApplication: stored }, result: { status: 200, body: { application: stored } } };
766
+ }
767
+ catch (error) {
768
+ return { result: { status: 409, body: { error: error instanceof Error ? error.message : "Workflow refused this review" } } };
769
+ }
770
+ });
771
+ sendJson(res, outcome.status, outcome.body);
772
+ return;
773
+ }
703
774
  // ---- Health ----
704
775
  if (pathname === "/health" && req.method === "GET") {
705
776
  sendJson(res, 200, { ok: true });
@@ -707,7 +778,7 @@ export async function startReviewConsoleServer(options) {
707
778
  }
708
779
  // ---- HTML shell (catch-all for GET) ----
709
780
  if (req.method === "GET" || req.method === "HEAD") {
710
- const html = buildConsoleHtml(sessionPath);
781
+ const html = buildConsoleHtml(sessionPath, Boolean(producerApply));
711
782
  send(res, 200, html, "text/html; charset=utf-8");
712
783
  return;
713
784
  }