-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattribution-store.js
More file actions
214 lines (186 loc) · 6.56 KB
/
attribution-store.js
File metadata and controls
214 lines (186 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/**
* Attribution Store (Milestone 4)
*
* Handles persistence of routing decision attribution records for
* outcome tracking and policy evaluation.
*/
import fs from "node:fs";
import path from "node:path";
import { DEFAULT_SWITCHBOARD_STATE_DIR } from "./paths.js";
export const DEFAULT_ATTRIBUTIONS_PATH = path.join(DEFAULT_SWITCHBOARD_STATE_DIR, "attributions");
function normalizeSessionId(sessionId) {
if (!sessionId || typeof sessionId !== "string") {
throw new Error("sessionId is required");
}
if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) {
throw new Error("sessionId contains invalid characters; allowed: A-Z a-z 0-9 . _ -");
}
return sessionId;
}
function readNdjson(filePath) {
if (!fs.existsSync(filePath)) return [];
return fs
.readFileSync(filePath, "utf8")
.trim()
.split("\n")
.filter(Boolean)
.map(JSON.parse);
}
/**
* Save an attribution record for a routing decision.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @param {object} params.attribution - attribution record with decisionId, confidence, etc.
* @returns {object} - saved record
*/
export function saveAttribution({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId,
attribution
}) {
const safeSessionId = normalizeSessionId(sessionId);
if (!attribution?.decisionId) {
throw new Error("attribution.decisionId is required");
}
const sessionFilePath = path.join(storePath, `${safeSessionId}.ndjson`);
const record = {
...attribution,
savedAt: new Date().toISOString()
};
fs.mkdirSync(path.dirname(sessionFilePath), { recursive: true });
fs.appendFileSync(sessionFilePath, `${JSON.stringify(record)}\n`, "utf8");
return record;
}
/**
* Load all attribution records for a session.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @returns {array} - array of attribution records
*/
export function loadSessionAttributions({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId
}) {
const safeSessionId = normalizeSessionId(sessionId);
const sessionFilePath = path.join(storePath, `${safeSessionId}.ndjson`);
return readNdjson(sessionFilePath);
}
/**
* Load attribution record by decision ID.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @param {string} params.decisionId - decision ID
* @returns {object|null} - attribution record or null if not found
*/
export function loadAttributionByDecisionId({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId,
decisionId
}) {
if (!decisionId) {
throw new Error("decisionId is required");
}
const safeSessionId = normalizeSessionId(sessionId);
const records = loadSessionAttributions({ storePath, sessionId: safeSessionId });
return records.find((r) => r.decisionId === decisionId) || null;
}
/**
* Update an attribution record with outcome feedback.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @param {string} params.decisionId - decision ID
* @param {object} params.outcome - outcome object with errorSignal, successSignal, etc.
* @returns {object} - updated record
*/
export function updateAttributionOutcome({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId,
decisionId,
outcome
}) {
if (!decisionId || !outcome) {
throw new Error("decisionId and outcome are required");
}
const safeSessionId = normalizeSessionId(sessionId);
const records = loadSessionAttributions({ storePath, sessionId: safeSessionId });
const index = records.findIndex((r) => r.decisionId === decisionId);
if (index === -1) {
throw new Error(`Attribution not found for decisionId ${decisionId}`);
}
records[index] = {
...records[index],
outcome,
updatedAt: new Date().toISOString()
};
const sessionFilePath = path.join(storePath, `${safeSessionId}.ndjson`);
const ndjson = records.map((r) => JSON.stringify(r)).join("\n") + "\n";
fs.writeFileSync(sessionFilePath, ndjson, "utf8");
return records[index];
}
/**
* Query attributions by outcome signal.
* Useful for filtering decisions that failed vs succeeded.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @param {string} params.errorSignal - error signal to filter by (e.g., "tool_failure")
* @returns {array} - matching attribution records
*/
export function queryAttributionsByErrorSignal({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId,
errorSignal
}) {
const safeSessionId = normalizeSessionId(sessionId);
const records = loadSessionAttributions({ storePath, sessionId: safeSessionId });
if (!errorSignal) {
return records;
}
return records.filter((r) => r.outcome?.errorSignal === errorSignal);
}
/**
* Get decision statistics for a session.
* @param {object} params
* @param {string} params.storePath - path to attributions directory
* @param {string} params.sessionId - session ID
* @returns {object} - statistics
*/
export function getSessionAttributionStats({
storePath = DEFAULT_ATTRIBUTIONS_PATH,
sessionId
}) {
const safeSessionId = normalizeSessionId(sessionId);
const records = loadSessionAttributions({ storePath, sessionId: safeSessionId });
const hasOutcomeSignal = (record) =>
Boolean(record?.outcome) && Object.prototype.hasOwnProperty.call(record.outcome, "errorSignal");
const successCount = records.filter((r) => hasOutcomeSignal(r) && r.outcome.errorSignal === null && r.outcome.executionStatus !== "planned").length;
const failureCount = records.filter((r) => hasOutcomeSignal(r) && r.outcome.errorSignal !== null).length;
const pendingCount = records.length - successCount - failureCount;
const avgConfidence = records.length > 0
? records.reduce((sum, r) => sum + (r.decisionConfidence || 0), 0) / records.length
: 0;
const failuresBySignal = {};
records.forEach((r) => {
const signal = !hasOutcomeSignal(r)
? "pending"
: r.outcome.errorSignal !== null
? r.outcome.errorSignal
: r.outcome.executionStatus === "planned"
? "pending"
: "success";
failuresBySignal[signal] = (failuresBySignal[signal] || 0) + 1;
});
return {
totalDecisions: records.length,
successCount,
failureCount,
pendingCount,
successRate: records.length > 0 ? successCount / records.length : 0,
avgConfidence,
failuresBySignal
};
}