@useody/feedback 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,198 @@
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 the 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 the 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 any 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.
185
+
186
+ Copyright 2026 Rodyr Inc.
187
+
188
+ Licensed under the Apache License, Version 2.0 (the "License");
189
+ you may not use this file except in compliance with the License.
190
+ You may obtain a copy of the License at
191
+
192
+ http://www.apache.org/licenses/LICENSE-2.0
193
+
194
+ Unless required by applicable law or agreed to in writing, software
195
+ distributed under the License is distributed on an "AS IS" BASIS,
196
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
197
+ See the License for the specific language governing permissions and
198
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @useody/feedback
2
+
3
+ Interaction signal collection, reputation scoring, and reward derivation for the Ody continuous learning pipeline.
4
+
5
+ ## Features
6
+
7
+ - **Signal collection** — thumbs up/down, corrections, Slack reactions
8
+ - **Reputation tracking** — per-source confidence scoring based on signal history
9
+ - **Reward derivation** — convert corrections into SFT/DPO training pairs
10
+ - **Conflict detection** — flag contradictory corrections before they enter training
11
+ - **Correction pipeline** — validate, process, and store user corrections
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { SignalCollector, ReputationTracker, deriveReward } from '@useody/feedback';
17
+ ```
18
+
19
+ ## License
20
+
21
+ Apache-2.0
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Detects conflicting corrections from different users.
3
+ * @module feedback/conflict-detector
4
+ */
5
+ import type { InteractionSignal } from './types.js';
6
+ /** A pair of corrections that contradict each other. */
7
+ export interface CorrectionConflict {
8
+ signalA: InteractionSignal;
9
+ signalB: InteractionSignal;
10
+ overlappingNodeIds: string[];
11
+ }
12
+ /**
13
+ * Detect conflicting corrections: pairs that reference the same topic
14
+ * (overlapping node IDs) but provide different correction text.
15
+ */
16
+ export declare function detectConflictingCorrections(corrections: InteractionSignal[]): CorrectionConflict[];
17
+ //# sourceMappingURL=conflict-detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conflict-detector.d.ts","sourceRoot":"","sources":["../src/conflict-detector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,wDAAwD;AACxD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,iBAAiB,CAAC;IAC3B,OAAO,EAAE,iBAAiB,CAAC;IAC3B,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,iBAAiB,EAAE,GAC/B,kBAAkB,EAAE,CAmCtB"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Detects conflicting corrections from different users.
3
+ * @module feedback/conflict-detector
4
+ */
5
+ /**
6
+ * Detect conflicting corrections: pairs that reference the same topic
7
+ * (overlapping node IDs) but provide different correction text.
8
+ */
9
+ export function detectConflictingCorrections(corrections) {
10
+ const correctionOnly = corrections.filter((s) => s.signalType === 'corrected' && s.correctionText);
11
+ const conflicts = [];
12
+ for (let i = 0; i < correctionOnly.length; i++) {
13
+ for (let j = i + 1; j < correctionOnly.length; j++) {
14
+ const a = correctionOnly[i];
15
+ const b = correctionOnly[j];
16
+ if (a.userId === b.userId) {
17
+ continue;
18
+ }
19
+ const overlapping = a.questionNodeIds.filter((id) => b.questionNodeIds.includes(id));
20
+ if (overlapping.length === 0) {
21
+ continue;
22
+ }
23
+ if (a.correctionText !== b.correctionText) {
24
+ conflicts.push({
25
+ signalA: a,
26
+ signalB: b,
27
+ overlappingNodeIds: overlapping,
28
+ });
29
+ }
30
+ }
31
+ }
32
+ return conflicts;
33
+ }
34
+ //# sourceMappingURL=conflict-detector.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Continuous correction-to-preference-pair pipeline.
3
+ * Every user correction becomes an immediate preference pair for Forge training.
4
+ * @module feedback/correction-pipeline
5
+ */
6
+ import type { PreferencePair } from '@useody/platform-core';
7
+ import type { PreferencePairStore } from './pair-store.js';
8
+ import type { ReputationTracker } from './reputation.js';
9
+ import type { CorrectionSignal } from './types.js';
10
+ /** Result of a correction pipeline validation. */
11
+ export interface CorrectionValidation {
12
+ valid: boolean;
13
+ reason?: string;
14
+ }
15
+ /**
16
+ * Validate that a correction signal is well-formed and usable.
17
+ * Rejects empty corrections, identical corrections, and UUID-only prompts.
18
+ */
19
+ export declare function validateCorrection(correction: CorrectionSignal): CorrectionValidation;
20
+ /**
21
+ * Process a single correction into a preference pair and store it.
22
+ * This is the continuous feedback loop: every valid correction from
23
+ * a sufficiently reputable user becomes an immediate training signal.
24
+ *
25
+ * @param correction - The enriched correction signal
26
+ * @param pairStore - Store for persisting preference pairs
27
+ * @param reputationTracker - Tracker for user reputation scores
28
+ * @returns The created preference pair, or null if rejected
29
+ */
30
+ export declare function processCorrection(correction: CorrectionSignal, pairStore: PreferencePairStore, reputationTracker: ReputationTracker): PreferencePair | null;
31
+ //# sourceMappingURL=correction-pipeline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"correction-pipeline.d.ts","sourceRoot":"","sources":["../src/correction-pipeline.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,KAAK,EAAE,gBAAgB,EAAmB,MAAM,YAAY,CAAC;AAEpE,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,gBAAgB,GAAG,oBAAoB,CAwBrF;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,gBAAgB,EAC5B,SAAS,EAAE,mBAAmB,EAC9B,iBAAiB,EAAE,iBAAiB,GACnC,cAAc,GAAG,IAAI,CAkBvB"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Continuous correction-to-preference-pair pipeline.
3
+ * Every user correction becomes an immediate preference pair for Forge training.
4
+ * @module feedback/correction-pipeline
5
+ */
6
+ import { derivePreferencePairFromCorrection, looksLikeUuid } from './reward-derivation.js';
7
+ /**
8
+ * Validate that a correction signal is well-formed and usable.
9
+ * Rejects empty corrections, identical corrections, and UUID-only prompts.
10
+ */
11
+ export function validateCorrection(correction) {
12
+ const { originalQuestion, originalAnswer, correctedAnswer } = correction;
13
+ if (!originalQuestion.trim()) {
14
+ return { valid: false, reason: 'Original question is empty' };
15
+ }
16
+ if (!originalAnswer.trim()) {
17
+ return { valid: false, reason: 'Original answer is empty' };
18
+ }
19
+ if (!correctedAnswer.trim()) {
20
+ return { valid: false, reason: 'Corrected answer is empty' };
21
+ }
22
+ if (correctedAnswer.trim() === originalAnswer.trim()) {
23
+ return { valid: false, reason: 'Corrected answer is identical to original' };
24
+ }
25
+ if (looksLikeUuid(originalQuestion)) {
26
+ return { valid: false, reason: 'Original question is a UUID, not natural language' };
27
+ }
28
+ return { valid: true };
29
+ }
30
+ /**
31
+ * Process a single correction into a preference pair and store it.
32
+ * This is the continuous feedback loop: every valid correction from
33
+ * a sufficiently reputable user becomes an immediate training signal.
34
+ *
35
+ * @param correction - The enriched correction signal
36
+ * @param pairStore - Store for persisting preference pairs
37
+ * @param reputationTracker - Tracker for user reputation scores
38
+ * @returns The created preference pair, or null if rejected
39
+ */
40
+ export function processCorrection(correction, pairStore, reputationTracker) {
41
+ const validation = validateCorrection(correction);
42
+ if (!validation.valid) {
43
+ return null;
44
+ }
45
+ const reputation = resolveReputation(correction.signal.userId, reputationTracker);
46
+ const pair = derivePreferencePairFromCorrection(correction, reputation);
47
+ if (!pair) {
48
+ return null;
49
+ }
50
+ pairStore.save(pair);
51
+ return pair;
52
+ }
53
+ /**
54
+ * Resolve reputation for a user, falling back to a default score
55
+ * if no reputation record exists yet (new users start at 0.5).
56
+ */
57
+ function resolveReputation(userId, tracker) {
58
+ const existing = tracker.getScore(userId);
59
+ if (existing) {
60
+ return existing;
61
+ }
62
+ return {
63
+ userId,
64
+ score: 0.5,
65
+ totalSignals: 0,
66
+ correctCorrections: 0,
67
+ overriddenCorrections: 0,
68
+ lastUpdated: new Date(),
69
+ };
70
+ }
71
+ //# sourceMappingURL=correction-pipeline.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @ody/feedback — interaction signals, reputation tracking, and reward derivation.
3
+ * @module @ody/feedback
4
+ */
5
+ export * from './types.js';
6
+ export { createFeedbackSchema } from './schema.js';
7
+ export { SignalCollector } from './signal-collector.js';
8
+ export { deriveReward, derivePreferencePair, derivePreferencePairFromCorrection, generateQuestionFromContent, generatePromptFromDetection, looksLikeUuid, } from './reward-derivation.js';
9
+ export { detectConflictingCorrections } from './conflict-detector.js';
10
+ export type { CorrectionConflict } from './conflict-detector.js';
11
+ export { processCorrection, validateCorrection, } from './correction-pipeline.js';
12
+ export type { CorrectionValidation } from './correction-pipeline.js';
13
+ export { ReputationTracker } from './reputation.js';
14
+ export type { ReputationThreshold } from './reputation.js';
15
+ export { PreferencePairStore } from './pair-store.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,kCAAkC,EAClC,2BAA2B,EAC3B,2BAA2B,EAC3B,aAAa,GACd,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AACtE,YAAY,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,YAAY,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @ody/feedback — interaction signals, reputation tracking, and reward derivation.
3
+ * @module @ody/feedback
4
+ */
5
+ export * from './types.js';
6
+ export { createFeedbackSchema } from './schema.js';
7
+ export { SignalCollector } from './signal-collector.js';
8
+ export { deriveReward, derivePreferencePair, derivePreferencePairFromCorrection, generateQuestionFromContent, generatePromptFromDetection, looksLikeUuid, } from './reward-derivation.js';
9
+ export { detectConflictingCorrections } from './conflict-detector.js';
10
+ export { processCorrection, validateCorrection, } from './correction-pipeline.js';
11
+ export { ReputationTracker } from './reputation.js';
12
+ export { PreferencePairStore } from './pair-store.js';
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Persists and queries DPO preference pairs in SQLite.
3
+ * @module feedback/pair-store
4
+ */
5
+ import type { PreferencePair } from '@useody/platform-core';
6
+ /**
7
+ * Store for DPO preference pairs backed by SQLite.
8
+ * Handles persistence, batch operations, and JSONL export.
9
+ */
10
+ export declare class PreferencePairStore {
11
+ private readonly db;
12
+ constructor(db: unknown);
13
+ /** Save a single preference pair. */
14
+ save(pair: PreferencePair): void;
15
+ /** Save multiple preference pairs in a single transaction. */
16
+ saveBatch(pairs: PreferencePair[]): void;
17
+ /** Find all preference pairs regardless of export status. */
18
+ findAll(): PreferencePair[];
19
+ /** Find all unexported preference pairs. */
20
+ findUnexported(): PreferencePair[];
21
+ /** Mark a list of pair IDs as exported. */
22
+ markExported(ids: string[]): void;
23
+ /** Count total preference pairs. */
24
+ count(): number;
25
+ /** Count unexported preference pairs. */
26
+ countUnexported(): number;
27
+ /**
28
+ * Export unexported pairs to a JSONL file and mark them as exported.
29
+ * Each line contains: {"prompt", "chosen", "rejected"}.
30
+ * @returns The number of pairs exported.
31
+ */
32
+ exportDpo(outputPath: string): number;
33
+ }
34
+ //# sourceMappingURL=pair-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pair-store.d.ts","sourceRoot":"","sources":["../src/pair-store.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAiB,MAAM,uBAAuB,CAAC;AAsE3E;;;GAGG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAW;gBAElB,EAAE,EAAE,OAAO;IAKvB,qCAAqC;IACrC,IAAI,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI;IAmBhC,8DAA8D;IAC9D,SAAS,CAAC,KAAK,EAAE,cAAc,EAAE,GAAG,IAAI;IA4BxC,6DAA6D;IAC7D,OAAO,IAAI,cAAc,EAAE;IAQ3B,4CAA4C;IAC5C,cAAc,IAAI,cAAc,EAAE;IAQlC,2CAA2C;IAC3C,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI;IASjC,oCAAoC;IACpC,KAAK,IAAI,MAAM;IAOf,yCAAyC;IACzC,eAAe,IAAI,MAAM;IAOzB;;;;OAIG;IACH,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM;CAsBtC"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Persists and queries DPO preference pairs in SQLite.
3
+ * @module feedback/pair-store
4
+ */
5
+ import crypto from 'node:crypto';
6
+ import { writeFileSync } from 'node:fs';
7
+ /** Ensure the preference_pairs table exists. */
8
+ function ensureTable(db) {
9
+ db.exec(`
10
+ CREATE TABLE IF NOT EXISTS preference_pairs (
11
+ id TEXT PRIMARY KEY NOT NULL,
12
+ prompt TEXT NOT NULL,
13
+ chosen TEXT NOT NULL,
14
+ rejected TEXT NOT NULL,
15
+ conflict_type TEXT NOT NULL,
16
+ resolved_by TEXT NOT NULL DEFAULT 'cli-user',
17
+ resolved_at TEXT NOT NULL DEFAULT (datetime('now')),
18
+ confidence REAL NOT NULL DEFAULT 1.0,
19
+ source_node_ids TEXT NOT NULL DEFAULT '[]',
20
+ exported INTEGER NOT NULL DEFAULT 0,
21
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
22
+ );
23
+ CREATE INDEX IF NOT EXISTS idx_pairs_exported
24
+ ON preference_pairs(exported);
25
+ CREATE INDEX IF NOT EXISTS idx_pairs_conflict_type
26
+ ON preference_pairs(conflict_type);
27
+ `);
28
+ }
29
+ /** Convert a raw row to a PreferencePair. */
30
+ function rowToPair(row) {
31
+ return {
32
+ prompt: row.prompt,
33
+ chosen: row.chosen,
34
+ rejected: row.rejected,
35
+ metadata: {
36
+ conflictType: row.conflict_type,
37
+ resolvedBy: row.resolved_by,
38
+ resolvedAt: new Date(row.resolved_at),
39
+ confidence: row.confidence,
40
+ sourceNodeIds: JSON.parse(row.source_node_ids),
41
+ },
42
+ };
43
+ }
44
+ /**
45
+ * Store for DPO preference pairs backed by SQLite.
46
+ * Handles persistence, batch operations, and JSONL export.
47
+ */
48
+ export class PreferencePairStore {
49
+ db;
50
+ constructor(db) {
51
+ this.db = db;
52
+ ensureTable(this.db);
53
+ }
54
+ /** Save a single preference pair. */
55
+ save(pair) {
56
+ const id = crypto.randomUUID();
57
+ this.db.prepare(`INSERT INTO preference_pairs
58
+ (id, prompt, chosen, rejected, conflict_type, resolved_by, resolved_at, confidence, source_node_ids)
59
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, pair.prompt, pair.chosen, pair.rejected, pair.metadata.conflictType, pair.metadata.resolvedBy, pair.metadata.resolvedAt.toISOString(), pair.metadata.confidence, JSON.stringify(pair.metadata.sourceNodeIds));
60
+ }
61
+ /** Save multiple preference pairs in a single transaction. */
62
+ saveBatch(pairs) {
63
+ if (pairs.length === 0)
64
+ return;
65
+ const stmt = this.db.prepare(`INSERT INTO preference_pairs
66
+ (id, prompt, chosen, rejected, conflict_type, resolved_by, resolved_at, confidence, source_node_ids)
67
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
68
+ const insertAll = this.db.transaction((items) => {
69
+ for (const pair of items) {
70
+ stmt.run(crypto.randomUUID(), pair.prompt, pair.chosen, pair.rejected, pair.metadata.conflictType, pair.metadata.resolvedBy, pair.metadata.resolvedAt.toISOString(), pair.metadata.confidence, JSON.stringify(pair.metadata.sourceNodeIds));
71
+ }
72
+ });
73
+ insertAll(pairs);
74
+ }
75
+ /** Find all preference pairs regardless of export status. */
76
+ findAll() {
77
+ const rows = this.db.prepare('SELECT * FROM preference_pairs ORDER BY created_at ASC').all();
78
+ return rows.map(rowToPair);
79
+ }
80
+ /** Find all unexported preference pairs. */
81
+ findUnexported() {
82
+ const rows = this.db.prepare('SELECT * FROM preference_pairs WHERE exported = 0 ORDER BY created_at ASC').all();
83
+ return rows.map(rowToPair);
84
+ }
85
+ /** Mark a list of pair IDs as exported. */
86
+ markExported(ids) {
87
+ if (ids.length === 0)
88
+ return;
89
+ const placeholders = ids.map(() => '?').join(',');
90
+ this.db.prepare(`UPDATE preference_pairs SET exported = 1 WHERE id IN (${placeholders})`).run(...ids);
91
+ }
92
+ /** Count total preference pairs. */
93
+ count() {
94
+ const row = this.db.prepare('SELECT COUNT(*) as cnt FROM preference_pairs').get();
95
+ return row.cnt;
96
+ }
97
+ /** Count unexported preference pairs. */
98
+ countUnexported() {
99
+ const row = this.db.prepare('SELECT COUNT(*) as cnt FROM preference_pairs WHERE exported = 0').get();
100
+ return row.cnt;
101
+ }
102
+ /**
103
+ * Export unexported pairs to a JSONL file and mark them as exported.
104
+ * Each line contains: {"prompt", "chosen", "rejected"}.
105
+ * @returns The number of pairs exported.
106
+ */
107
+ exportDpo(outputPath) {
108
+ const rows = this.db.prepare('SELECT * FROM preference_pairs WHERE exported = 0 ORDER BY created_at ASC').all();
109
+ if (rows.length === 0)
110
+ return 0;
111
+ const lines = rows.map((row) => JSON.stringify({
112
+ prompt: row.prompt,
113
+ chosen: row.chosen,
114
+ rejected: row.rejected,
115
+ }));
116
+ writeFileSync(outputPath, lines.join('\n') + '\n', 'utf-8');
117
+ const ids = rows.map((r) => r.id);
118
+ this.markExported(ids);
119
+ return rows.length;
120
+ }
121
+ }
122
+ //# sourceMappingURL=pair-store.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Tracks and computes user reputation scores.
3
+ * @module feedback/reputation
4
+ */
5
+ import type Database from 'better-sqlite3';
6
+ import type { ReputationScore } from './types.js';
7
+ /** Threshold label for a user's reputation. */
8
+ export type ReputationThreshold = 'trusted' | 'normal' | 'untrusted';
9
+ /** Tracks user reputation based on interaction signal history. */
10
+ export declare class ReputationTracker {
11
+ private readonly db;
12
+ constructor(db: Database.Database);
13
+ /**
14
+ * Calculate reputation score from signal history.
15
+ * Formula: (correctCorrections * 2 + shared - rejected - escalated) / (totalSignals + 10)
16
+ * Clamped to 0-1.
17
+ */
18
+ calculate(userId: string): number;
19
+ /** Get the stored reputation score for a user. */
20
+ getScore(userId: string): ReputationScore | null;
21
+ /** Recalculate and store the reputation score. */
22
+ update(userId: string): ReputationScore;
23
+ /** Get the threshold label for a user's reputation. */
24
+ getThreshold(userId: string): ReputationThreshold;
25
+ }
26
+ //# sourceMappingURL=reputation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reputation.d.ts","sourceRoot":"","sources":["../src/reputation.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,QAAQ,MAAM,gBAAgB,CAAC;AAC3C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,+CAA+C;AAC/C,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC;AAErE,kEAAkE;AAClE,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAoB;gBAE3B,EAAE,EAAE,QAAQ,CAAC,QAAQ;IAIjC;;;;OAIG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAwBjC,kDAAkD;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,GAAG,IAAI;IAUhD,kDAAkD;IAClD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe;IAgCvC,uDAAuD;IACvD,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,mBAAmB;CAMlD"}
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Tracks and computes user reputation scores.
3
+ * @module feedback/reputation
4
+ */
5
+ /** Tracks user reputation based on interaction signal history. */
6
+ export class ReputationTracker {
7
+ db;
8
+ constructor(db) {
9
+ this.db = db;
10
+ }
11
+ /**
12
+ * Calculate reputation score from signal history.
13
+ * Formula: (correctCorrections * 2 + shared - rejected - escalated) / (totalSignals + 10)
14
+ * Clamped to 0-1.
15
+ */
16
+ calculate(userId) {
17
+ const rows = this.db.prepare('SELECT signal_type, COUNT(*) as cnt FROM interaction_signals WHERE user_id = ? GROUP BY signal_type').all(userId);
18
+ const counts = {};
19
+ let totalSignals = 0;
20
+ for (const row of rows) {
21
+ counts[row.signal_type] = row.cnt;
22
+ totalSignals += row.cnt;
23
+ }
24
+ const shared = counts['shared'] ?? 0;
25
+ const rejected = counts['rejected'] ?? 0;
26
+ const escalated = counts['escalated'] ?? 0;
27
+ const corrected = counts['corrected'] ?? 0;
28
+ const numerator = corrected * 2 + shared - rejected - escalated;
29
+ const denominator = totalSignals + 10;
30
+ const raw = numerator / denominator;
31
+ return Math.min(1, Math.max(0, raw));
32
+ }
33
+ /** Get the stored reputation score for a user. */
34
+ getScore(userId) {
35
+ const row = this.db.prepare('SELECT * FROM user_reputation WHERE user_id = ?').get(userId);
36
+ if (!row)
37
+ return null;
38
+ return rowToReputation(row);
39
+ }
40
+ /** Recalculate and store the reputation score. */
41
+ update(userId) {
42
+ const score = this.calculate(userId);
43
+ const signalCounts = this.db.prepare('SELECT signal_type, COUNT(*) as cnt FROM interaction_signals WHERE user_id = ? GROUP BY signal_type').all(userId);
44
+ const counts = toCountMap(signalCounts);
45
+ const totalSignals = Object.values(counts).reduce((a, b) => a + b, 0);
46
+ const now = new Date();
47
+ this.db.prepare(`
48
+ INSERT INTO user_reputation (user_id, score, total_signals, correct_corrections, overridden_corrections, last_updated)
49
+ VALUES (?, ?, ?, ?, ?, ?)
50
+ ON CONFLICT(user_id) DO UPDATE SET
51
+ score = excluded.score,
52
+ total_signals = excluded.total_signals,
53
+ correct_corrections = excluded.correct_corrections,
54
+ overridden_corrections = excluded.overridden_corrections,
55
+ last_updated = excluded.last_updated
56
+ `).run(userId, score, totalSignals, counts['corrected'] ?? 0, 0, now.toISOString());
57
+ return {
58
+ userId,
59
+ score,
60
+ totalSignals,
61
+ correctCorrections: counts['corrected'] ?? 0,
62
+ overriddenCorrections: 0,
63
+ lastUpdated: now,
64
+ };
65
+ }
66
+ /** Get the threshold label for a user's reputation. */
67
+ getThreshold(userId) {
68
+ const score = this.calculate(userId);
69
+ if (score >= 0.8)
70
+ return 'trusted';
71
+ if (score >= 0.4)
72
+ return 'normal';
73
+ return 'untrusted';
74
+ }
75
+ }
76
+ function rowToReputation(row) {
77
+ return {
78
+ userId: row.user_id,
79
+ score: row.score,
80
+ totalSignals: row.total_signals,
81
+ correctCorrections: row.correct_corrections,
82
+ overriddenCorrections: row.overridden_corrections,
83
+ lastUpdated: new Date(row.last_updated),
84
+ };
85
+ }
86
+ function toCountMap(rows) {
87
+ const map = {};
88
+ for (const row of rows) {
89
+ map[row.signal_type] = row.cnt;
90
+ }
91
+ return map;
92
+ }
93
+ //# sourceMappingURL=reputation.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Derives rewards and preference pairs from interaction signals.
3
+ * @module feedback/reward-derivation
4
+ */
5
+ import type { Detection, KnowledgeNode, PreferencePair } from '@useody/platform-core';
6
+ import type { CorrectionSignal, InteractionSignal, ReputationScore, RewardDerivation } from './types.js';
7
+ /**
8
+ * Derive a reward from an interaction signal, factoring in user reputation.
9
+ */
10
+ export declare function deriveReward(signal: InteractionSignal, reputation: ReputationScore): RewardDerivation;
11
+ /**
12
+ * Generate a topic-based question from node content when no original question is available.
13
+ * Extracts a meaningful topic from the content to create a natural question.
14
+ */
15
+ export declare function generateQuestionFromContent(content: string): string;
16
+ /**
17
+ * Generate a natural language prompt from a detection and its referenced nodes.
18
+ * Extracts the topic from the detection description or node titles to form a question.
19
+ * Returns null if no meaningful prompt can be derived.
20
+ */
21
+ export declare function generatePromptFromDetection(detection: Detection, nodes: KnowledgeNode[]): string | null;
22
+ /**
23
+ * Check whether a string looks like a UUID or a comma-separated list of UUIDs.
24
+ * Used to prevent UUID-based prompts from leaking into training data.
25
+ */
26
+ export declare function looksLikeUuid(text: string): boolean;
27
+ /**
28
+ * Derive a preference pair from a correction signal.
29
+ * Only generates pairs for 'corrected' signals with sufficient reputation.
30
+ * Returns null if reputation is below 0.4 (queued for review),
31
+ * or if no meaningful prompt can be generated (avoids UUID-based prompts).
32
+ *
33
+ * @param signal - The interaction signal
34
+ * @param originalAnswer - The model's original response
35
+ * @param correctedText - The user's corrected text
36
+ * @param reputation - The correcting user's reputation
37
+ * @param originalQuestion - The actual user question (optional)
38
+ * @param nodeContent - Content from referenced nodes for question generation (optional)
39
+ */
40
+ export declare function derivePreferencePair(signal: InteractionSignal, originalAnswer: string, correctedText: string, reputation: ReputationScore, originalQuestion?: string, nodeContent?: string): PreferencePair | null;
41
+ /**
42
+ * Derive a preference pair directly from a correction signal.
43
+ * Simpler than detection-based pairs: the user already provided
44
+ * the chosen (corrected) and rejected (original) responses.
45
+ * No LLM call needed.
46
+ *
47
+ * @param correction - The enriched correction signal
48
+ * @param reputation - The correcting user's reputation score
49
+ * @returns A preference pair, or null if reputation is too low or prompt is invalid
50
+ */
51
+ export declare function derivePreferencePairFromCorrection(correction: CorrectionSignal, reputation: ReputationScore): PreferencePair | null;
52
+ //# sourceMappingURL=reward-derivation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reward-derivation.d.ts","sourceRoot":"","sources":["../src/reward-derivation.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAMpB;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,EAAE,UAAU,EAAE,eAAe,GAAG,gBAAgB,CA+CrG;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAInE;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,SAAS,EAAE,SAAS,EACpB,KAAK,EAAE,aAAa,EAAE,GACrB,MAAM,GAAG,IAAI,CA8Bf;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGnD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,iBAAiB,EACzB,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,eAAe,EAC3B,gBAAgB,CAAC,EAAE,MAAM,EACzB,WAAW,CAAC,EAAE,MAAM,GACnB,cAAc,GAAG,IAAI,CAmCvB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kCAAkC,CAChD,UAAU,EAAE,gBAAgB,EAC5B,UAAU,EAAE,eAAe,GAC1B,cAAc,GAAG,IAAI,CAyBvB"}
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Derives rewards and preference pairs from interaction signals.
3
+ * @module feedback/reward-derivation
4
+ */
5
+ import { SIGNAL_WEIGHTS } from './types.js';
6
+ /** UUID v4 pattern used to detect invalid prompt content. */
7
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ /**
9
+ * Derive a reward from an interaction signal, factoring in user reputation.
10
+ */
11
+ export function deriveReward(signal, reputation) {
12
+ const weights = SIGNAL_WEIGHTS[signal.signalType];
13
+ const adjustedWeight = weights.weight * reputation.score;
14
+ let reason;
15
+ switch (signal.signalType) {
16
+ case 'accepted':
17
+ reason = 'User accepted the answer';
18
+ break;
19
+ case 'rejected':
20
+ reason = 'User rejected the answer';
21
+ break;
22
+ case 'corrected':
23
+ reason = `User provided correction (reputation: ${reputation.score.toFixed(2)})`;
24
+ break;
25
+ case 'escalated':
26
+ reason = 'User escalated to another source';
27
+ break;
28
+ case 'shared':
29
+ reason = 'User shared the answer with others';
30
+ break;
31
+ case 'follow_up':
32
+ reason = 'User asked a follow-up question';
33
+ break;
34
+ case 'emoji_positive':
35
+ reason = 'Positive emoji reaction (thumbsup, check, heart)';
36
+ break;
37
+ case 'emoji_negative':
38
+ reason = 'Negative emoji reaction (thumbsdown, x, confused)';
39
+ break;
40
+ case 'reply_positive':
41
+ reason = 'Reply with positive sentiment';
42
+ break;
43
+ case 'reply_negative':
44
+ reason = 'Reply with negative sentiment';
45
+ break;
46
+ default:
47
+ reason = `Signal: ${signal.signalType}`;
48
+ }
49
+ return {
50
+ signalId: signal.id,
51
+ rewardType: weights.type,
52
+ weight: Math.min(1, Math.max(0, adjustedWeight)),
53
+ preferencePairGenerated: false,
54
+ reason,
55
+ };
56
+ }
57
+ /**
58
+ * Generate a topic-based question from node content when no original question is available.
59
+ * Extracts a meaningful topic from the content to create a natural question.
60
+ */
61
+ export function generateQuestionFromContent(content) {
62
+ const firstLine = content.split('\n')[0]?.trim() ?? '';
63
+ const topic = firstLine.length > 80 ? firstLine.slice(0, 80) : firstLine;
64
+ return `What is the current policy on ${topic}?`;
65
+ }
66
+ /**
67
+ * Generate a natural language prompt from a detection and its referenced nodes.
68
+ * Extracts the topic from the detection description or node titles to form a question.
69
+ * Returns null if no meaningful prompt can be derived.
70
+ */
71
+ export function generatePromptFromDetection(detection, nodes) {
72
+ // Try to extract topic from the detection description
73
+ const desc = detection.description.trim();
74
+ if (desc.length > 0) {
75
+ // Use the detection description to form a targeted question
76
+ const topic = desc.length > 120 ? desc.slice(0, 120) : desc;
77
+ return `What is the correct information regarding: ${topic}`;
78
+ }
79
+ // Fall back to node titles
80
+ const titles = nodes
81
+ .filter((n) => detection.nodeIds.includes(n.id))
82
+ .map((n) => n.title)
83
+ .filter((t) => t.trim().length > 0);
84
+ if (titles.length > 0) {
85
+ return `What is the current policy on ${titles.join(' and ')}?`;
86
+ }
87
+ // Fall back to node content summaries
88
+ const summaries = nodes
89
+ .filter((n) => detection.nodeIds.includes(n.id))
90
+ .map((n) => n.content.summary)
91
+ .filter((s) => s.trim().length > 0);
92
+ if (summaries.length > 0) {
93
+ return generateQuestionFromContent(summaries[0]);
94
+ }
95
+ return null;
96
+ }
97
+ /**
98
+ * Check whether a string looks like a UUID or a comma-separated list of UUIDs.
99
+ * Used to prevent UUID-based prompts from leaking into training data.
100
+ */
101
+ export function looksLikeUuid(text) {
102
+ const parts = text.split(/[, ]+/).map((s) => s.trim()).filter((s) => s.length > 0);
103
+ return parts.length > 0 && parts.every((p) => UUID_V4_PATTERN.test(p));
104
+ }
105
+ /**
106
+ * Derive a preference pair from a correction signal.
107
+ * Only generates pairs for 'corrected' signals with sufficient reputation.
108
+ * Returns null if reputation is below 0.4 (queued for review),
109
+ * or if no meaningful prompt can be generated (avoids UUID-based prompts).
110
+ *
111
+ * @param signal - The interaction signal
112
+ * @param originalAnswer - The model's original response
113
+ * @param correctedText - The user's corrected text
114
+ * @param reputation - The correcting user's reputation
115
+ * @param originalQuestion - The actual user question (optional)
116
+ * @param nodeContent - Content from referenced nodes for question generation (optional)
117
+ */
118
+ export function derivePreferencePair(signal, originalAnswer, correctedText, reputation, originalQuestion, nodeContent) {
119
+ if (signal.signalType !== 'corrected') {
120
+ return null;
121
+ }
122
+ if (reputation.score < 0.4) {
123
+ return null;
124
+ }
125
+ const confidence = reputation.score >= 0.8 ? 1.0 : 0.6;
126
+ let prompt = null;
127
+ if (originalQuestion && !looksLikeUuid(originalQuestion)) {
128
+ prompt = originalQuestion;
129
+ }
130
+ else if (nodeContent) {
131
+ prompt = generateQuestionFromContent(nodeContent);
132
+ }
133
+ // If no prompt could be derived, return null rather than embedding UUIDs
134
+ if (!prompt) {
135
+ return null;
136
+ }
137
+ return {
138
+ prompt,
139
+ chosen: correctedText,
140
+ rejected: originalAnswer,
141
+ metadata: {
142
+ conflictType: 'contradiction',
143
+ resolvedBy: signal.userId,
144
+ resolvedAt: signal.createdAt,
145
+ confidence,
146
+ sourceNodeIds: signal.questionNodeIds,
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * Derive a preference pair directly from a correction signal.
152
+ * Simpler than detection-based pairs: the user already provided
153
+ * the chosen (corrected) and rejected (original) responses.
154
+ * No LLM call needed.
155
+ *
156
+ * @param correction - The enriched correction signal
157
+ * @param reputation - The correcting user's reputation score
158
+ * @returns A preference pair, or null if reputation is too low or prompt is invalid
159
+ */
160
+ export function derivePreferencePairFromCorrection(correction, reputation) {
161
+ if (reputation.score < 0.4) {
162
+ return null;
163
+ }
164
+ const { originalQuestion, originalAnswer, correctedAnswer, signal } = correction;
165
+ if (looksLikeUuid(originalQuestion)) {
166
+ return null;
167
+ }
168
+ const confidence = reputation.score >= 0.8 ? 1.0 : 0.6;
169
+ return {
170
+ prompt: originalQuestion,
171
+ chosen: correctedAnswer,
172
+ rejected: originalAnswer,
173
+ metadata: {
174
+ conflictType: 'contradiction',
175
+ resolvedBy: signal.userId,
176
+ resolvedAt: signal.createdAt,
177
+ confidence,
178
+ sourceNodeIds: signal.questionNodeIds,
179
+ },
180
+ };
181
+ }
182
+ //# sourceMappingURL=reward-derivation.js.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * SQLite schema for the feedback package.
3
+ * @module feedback/schema
4
+ */
5
+ import type Database from 'better-sqlite3';
6
+ /**
7
+ * Create feedback tables in the given SQLite database.
8
+ * Creates interaction_signals and user_reputation tables.
9
+ */
10
+ export declare function createFeedbackSchema(db: Database.Database): void;
11
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,QAAQ,MAAM,gBAAgB,CAAC;AAE3C;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CA4BhE"}
package/dist/schema.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * SQLite schema for the feedback package.
3
+ * @module feedback/schema
4
+ */
5
+ /**
6
+ * Create feedback tables in the given SQLite database.
7
+ * Creates interaction_signals and user_reputation tables.
8
+ */
9
+ export function createFeedbackSchema(db) {
10
+ db.exec(`
11
+ CREATE TABLE IF NOT EXISTS interaction_signals (
12
+ id TEXT PRIMARY KEY,
13
+ user_id TEXT NOT NULL,
14
+ conversation_id TEXT NOT NULL,
15
+ turn_id TEXT NOT NULL,
16
+ signal_type TEXT NOT NULL CHECK(signal_type IN ('accepted','rejected','corrected','escalated','shared','follow_up','emoji_positive','emoji_negative','reply_positive','reply_negative')),
17
+ correction_text TEXT,
18
+ question_node_ids TEXT NOT NULL DEFAULT '[]',
19
+ time_to_action_ms INTEGER NOT NULL,
20
+ reputation_weight REAL NOT NULL DEFAULT 1.0,
21
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
22
+ );
23
+
24
+ CREATE INDEX IF NOT EXISTS idx_signals_user_id ON interaction_signals(user_id);
25
+ CREATE INDEX IF NOT EXISTS idx_signals_conversation_id ON interaction_signals(conversation_id);
26
+ CREATE INDEX IF NOT EXISTS idx_signals_signal_type ON interaction_signals(signal_type);
27
+
28
+ CREATE TABLE IF NOT EXISTS user_reputation (
29
+ user_id TEXT PRIMARY KEY,
30
+ score REAL NOT NULL DEFAULT 0.5,
31
+ total_signals INTEGER NOT NULL DEFAULT 0,
32
+ correct_corrections INTEGER NOT NULL DEFAULT 0,
33
+ overridden_corrections INTEGER NOT NULL DEFAULT 0,
34
+ last_updated TEXT NOT NULL DEFAULT (datetime('now'))
35
+ );
36
+ `);
37
+ }
38
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Collects and queries interaction signals from users.
3
+ * @module feedback/signal-collector
4
+ */
5
+ import type Database from 'better-sqlite3';
6
+ import type { InteractionSignal, SignalType } from './types.js';
7
+ /** Collects user interaction signals into SQLite. */
8
+ export declare class SignalCollector {
9
+ private readonly db;
10
+ constructor(db: Database.Database);
11
+ /** Record a new interaction signal. */
12
+ record(signal: Omit<InteractionSignal, 'id' | 'createdAt'>): InteractionSignal;
13
+ /** Find all signals for a conversation. */
14
+ findByConversation(conversationId: string): InteractionSignal[];
15
+ /** Find recent signals for a user. */
16
+ findByUser(userId: string, limit?: number): InteractionSignal[];
17
+ /** Count signals by type for a user. */
18
+ countByType(userId: string): Record<SignalType, number>;
19
+ }
20
+ //# sourceMappingURL=signal-collector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal-collector.d.ts","sourceRoot":"","sources":["../src/signal-collector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,QAAQ,MAAM,gBAAgB,CAAC;AAE3C,OAAO,KAAK,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEhE,qDAAqD;AACrD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAoB;gBAE3B,EAAE,EAAE,QAAQ,CAAC,QAAQ;IAIjC,uCAAuC;IACvC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,IAAI,GAAG,WAAW,CAAC,GAAG,iBAAiB;IAwB9E,2CAA2C;IAC3C,kBAAkB,CAAC,cAAc,EAAE,MAAM,GAAG,iBAAiB,EAAE;IAQ/D,sCAAsC;IACtC,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,iBAAiB,EAAE;IAQ5D,wCAAwC;IACxC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC;CAkBxD"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Collects and queries interaction signals from users.
3
+ * @module feedback/signal-collector
4
+ */
5
+ import crypto from 'node:crypto';
6
+ /** Collects user interaction signals into SQLite. */
7
+ export class SignalCollector {
8
+ db;
9
+ constructor(db) {
10
+ this.db = db;
11
+ }
12
+ /** Record a new interaction signal. */
13
+ record(signal) {
14
+ const id = crypto.randomUUID();
15
+ const createdAt = new Date();
16
+ this.db.prepare(`
17
+ INSERT INTO interaction_signals
18
+ (id, user_id, conversation_id, turn_id, signal_type, correction_text, question_node_ids, time_to_action_ms, reputation_weight, created_at)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
20
+ `).run(id, signal.userId, signal.conversationId, signal.turnId, signal.signalType, signal.correctionText ?? null, JSON.stringify(signal.questionNodeIds), signal.timeToActionMs, signal.reputationWeight, createdAt.toISOString());
21
+ return { id, createdAt, ...signal };
22
+ }
23
+ /** Find all signals for a conversation. */
24
+ findByConversation(conversationId) {
25
+ const rows = this.db.prepare('SELECT * FROM interaction_signals WHERE conversation_id = ? ORDER BY created_at ASC').all(conversationId);
26
+ return rows.map(rowToSignal);
27
+ }
28
+ /** Find recent signals for a user. */
29
+ findByUser(userId, limit = 100) {
30
+ const rows = this.db.prepare('SELECT * FROM interaction_signals WHERE user_id = ? ORDER BY created_at DESC LIMIT ?').all(userId, limit);
31
+ return rows.map(rowToSignal);
32
+ }
33
+ /** Count signals by type for a user. */
34
+ countByType(userId) {
35
+ const rows = this.db.prepare('SELECT signal_type, COUNT(*) as cnt FROM interaction_signals WHERE user_id = ? GROUP BY signal_type').all(userId);
36
+ const result = {
37
+ accepted: 0, rejected: 0, corrected: 0,
38
+ escalated: 0, shared: 0, follow_up: 0,
39
+ emoji_positive: 0, emoji_negative: 0,
40
+ reply_positive: 0, reply_negative: 0,
41
+ };
42
+ for (const row of rows) {
43
+ result[row.signal_type] = row.cnt;
44
+ }
45
+ return result;
46
+ }
47
+ }
48
+ function rowToSignal(row) {
49
+ return {
50
+ id: row.id,
51
+ userId: row.user_id,
52
+ conversationId: row.conversation_id,
53
+ turnId: row.turn_id,
54
+ signalType: row.signal_type,
55
+ correctionText: row.correction_text ?? undefined,
56
+ questionNodeIds: JSON.parse(row.question_node_ids),
57
+ timeToActionMs: row.time_to_action_ms,
58
+ reputationWeight: row.reputation_weight,
59
+ createdAt: new Date(row.created_at),
60
+ };
61
+ }
62
+ //# sourceMappingURL=signal-collector.js.map
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Feedback package types for interaction signals, reputation, and rewards.
3
+ * @module feedback/types
4
+ */
5
+ /** Types of user interaction signals. */
6
+ export type SignalType = 'accepted' | 'rejected' | 'corrected' | 'escalated' | 'shared' | 'follow_up' | 'emoji_positive' | 'emoji_negative' | 'reply_positive' | 'reply_negative';
7
+ /** A recorded user interaction signal. */
8
+ export interface InteractionSignal {
9
+ id: string;
10
+ userId: string;
11
+ conversationId: string;
12
+ turnId: string;
13
+ signalType: SignalType;
14
+ correctionText?: string;
15
+ questionNodeIds: string[];
16
+ timeToActionMs: number;
17
+ reputationWeight: number;
18
+ createdAt: Date;
19
+ }
20
+ /** A user's reputation score and history. */
21
+ export interface ReputationScore {
22
+ userId: string;
23
+ score: number;
24
+ totalSignals: number;
25
+ correctCorrections: number;
26
+ overriddenCorrections: number;
27
+ lastUpdated: Date;
28
+ }
29
+ /** Derived reward from an interaction signal. */
30
+ export interface RewardDerivation {
31
+ signalId: string;
32
+ rewardType: 'positive' | 'negative' | 'neutral';
33
+ weight: number;
34
+ preferencePairGenerated: boolean;
35
+ reason: string;
36
+ }
37
+ /**
38
+ * A correction signal with the full context needed for preference pair creation.
39
+ * This is the enriched version of an InteractionSignal with type 'corrected'.
40
+ */
41
+ export interface CorrectionSignal {
42
+ /** The underlying interaction signal. */
43
+ signal: InteractionSignal;
44
+ /** The original question the user asked. */
45
+ originalQuestion: string;
46
+ /** Colleague's original answer (becomes the rejected response). */
47
+ originalAnswer: string;
48
+ /** The user's corrected answer (becomes the chosen response). */
49
+ correctedAnswer: string;
50
+ }
51
+ /** Signal weights for reward derivation. */
52
+ export declare const SIGNAL_WEIGHTS: Record<SignalType, {
53
+ type: 'positive' | 'negative' | 'neutral';
54
+ weight: number;
55
+ }>;
56
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,yCAAyC;AACzC,MAAM,MAAM,UAAU,GAClB,UAAU,GACV,UAAU,GACV,WAAW,GACX,WAAW,GACX,QAAQ,GACR,WAAW,GACX,gBAAgB,GAChB,gBAAgB,GAChB,gBAAgB,GAChB,gBAAgB,CAAC;AAErB,0CAA0C;AAC1C,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,UAAU,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,WAAW,EAAE,IAAI,CAAC;CACnB;AAED,iDAAiD;AACjD,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS,CAAC;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,uBAAuB,EAAE,OAAO,CAAC;IACjC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,yCAAyC;IACzC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,4CAA4C;IAC5C,gBAAgB,EAAE,MAAM,CAAC;IACzB,mEAAmE;IACnE,cAAc,EAAE,MAAM,CAAC;IACvB,iEAAiE;IACjE,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,4CAA4C;AAC5C,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAa5G,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Feedback package types for interaction signals, reputation, and rewards.
3
+ * @module feedback/types
4
+ */
5
+ /** Signal weights for reward derivation. */
6
+ export const SIGNAL_WEIGHTS = {
7
+ // Explicit interaction signals
8
+ accepted: { type: 'positive', weight: 0.3 },
9
+ rejected: { type: 'negative', weight: 0.6 },
10
+ corrected: { type: 'negative', weight: 0.9 },
11
+ escalated: { type: 'negative', weight: 0.5 },
12
+ shared: { type: 'positive', weight: 0.8 },
13
+ follow_up: { type: 'neutral', weight: 0.1 },
14
+ // Passive sentiment signals (emoji reactions, reply tone)
15
+ emoji_positive: { type: 'positive', weight: 0.4 },
16
+ emoji_negative: { type: 'negative', weight: 0.5 },
17
+ reply_positive: { type: 'positive', weight: 0.5 },
18
+ reply_negative: { type: 'negative', weight: 0.6 },
19
+ };
20
+ //# sourceMappingURL=types.js.map
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@useody/feedback",
3
+ "description": "Interaction signal collection, reputation scoring, and reward derivation for continuous learning",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "test": "vitest run",
17
+ "typecheck": "tsc --noEmit",
18
+ "lint": "eslint src/",
19
+ "clean": "rm -rf dist",
20
+ "prepublishOnly": "pnpm build"
21
+ },
22
+ "dependencies": {
23
+ "@useody/platform-core": "workspace:*",
24
+ "better-sqlite3": "^11.8.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/better-sqlite3": "^7.6.0",
28
+ "vitest": "^3.0.0",
29
+ "typescript": "^5.7.0"
30
+ },
31
+ "engines": {
32
+ "node": ">=20.0.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "license": "Apache-2.0",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/ufukkaraca/ody-platform.git",
41
+ "directory": "packages/feedback"
42
+ },
43
+ "files": [
44
+ "dist/**/*.js",
45
+ "dist/**/*.d.ts",
46
+ "dist/**/*.d.ts.map",
47
+ "README.md",
48
+ "LICENSE"
49
+ ]
50
+ }