@trazum/core 2.5.2 → 2.6.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.
@@ -0,0 +1,283 @@
1
+ import { claudeCodeRecords } from './claude-code.js';
2
+ import { codexRecords } from './codex.js';
3
+ import { MAX_INPUT_CHARS } from './limits.js';
4
+ import { BUNDLED_CATALOGUE } from './pricing.js';
5
+ import { parseUsageLine, profileUsage } from './usage.js';
6
+ import { TASK_LIMITATIONS } from './task-types.js';
7
+ import type { TaskCategory, TaskFinding, TaskFormat, TaskInput, TaskReport } from './task-types.js';
8
+
9
+ export const taskObject = (value: unknown): value is Record<string, unknown> =>
10
+ typeof value === 'object' && value !== null && !Array.isArray(value);
11
+
12
+ export function taskError(): never { throw new Error('Invalid task data. See the task workflow schema and limits.'); }
13
+
14
+ export function taskKeys(value: unknown, allowed: readonly string[]): asserts value is Record<string, unknown> {
15
+ if (!taskObject(value) || Object.keys(value).some((key) => !allowed.includes(key))) taskError();
16
+ }
17
+
18
+ export const taskText = (value: unknown, max: number): value is string =>
19
+ typeof value === 'string' && value.trim() !== '' && value.length <= max && !/[\u0000-\u001f\u007f]/u.test(value);
20
+ export const taskId = (value: unknown): value is string =>
21
+ typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/u.test(value);
22
+
23
+ function validateInput(value: unknown): TaskInput {
24
+ taskKeys(value, ['taskId', 'taskType', 'criterion', 'policyId', 'outcome', 'assessor', 'sources']);
25
+ if (!taskId(value.taskId) || !taskId(value.taskType) || !taskText(value.criterion, 500) ||
26
+ (value.policyId !== undefined && value.policyId !== 'baseline' && value.policyId !== 'repeat-review-v1') ||
27
+ (value.outcome !== undefined && (typeof value.outcome !== 'string' || !['accepted', 'rejected', 'unknown'].includes(value.outcome))) ||
28
+ (value.assessor !== undefined && !taskText(value.assessor, 100)) ||
29
+ ((value.outcome === 'accepted' || value.outcome === 'rejected') && !taskText(value.assessor, 100)) ||
30
+ !Array.isArray(value.sources) || value.sources.length < 1 || value.sources.length > 16) taskError();
31
+ let size = 0;
32
+ for (const source of value.sources) {
33
+ taskKeys(source, ['format', 'text']);
34
+ if ((source.format !== 'claude-code' && source.format !== 'codex') || typeof source.text !== 'string' || !source.text.trim()) taskError();
35
+ size += source.text.length;
36
+ if (size > MAX_INPUT_CHARS) taskError();
37
+ }
38
+ return value as unknown as TaskInput;
39
+ }
40
+
41
+ /** Only used to refuse possible reuse. A collision withholds a verdict. */
42
+ function fingerprint(text: string): string {
43
+ let a = 0x811c9dc5;
44
+ let b = 0x9e3779b9;
45
+ for (let i = 0; i < text.length; i++) {
46
+ a = Math.imul(a ^ text.charCodeAt(i), 0x01000193);
47
+ b = Math.imul(b ^ text.charCodeAt(i), 0x85ebca6b);
48
+ }
49
+ return `${(a >>> 0).toString(16).padStart(8, '0')}${(b >>> 0).toString(16).padStart(8, '0')}`;
50
+ }
51
+
52
+ function canonical(value: unknown, depth = 0): string {
53
+ if (depth > 40) taskError();
54
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
55
+ if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
56
+ if (Array.isArray(value)) return `[${value.map((item) => canonical(item, depth + 1)).join(',')}]`;
57
+ if (taskObject(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key], depth + 1)}`).join(',')}}`;
58
+ taskError();
59
+ }
60
+
61
+ function category(name: string): TaskCategory {
62
+ if (['Read', 'read_file', 'read_text_file'].includes(name)) return 'read';
63
+ if (['Grep', 'Glob', 'grep', 'search', 'search_files', 'list_files'].includes(name)) return 'search';
64
+ if (['Bash', 'exec_command', 'shell_command', 'shell'].includes(name)) return 'shell';
65
+ return 'other';
66
+ }
67
+
68
+ type Call = { key: string; name: string; namespace: string | null; category: TaskCategory; line: number; resultLine?: number; result?: string; failed?: boolean; conflict: boolean };
69
+ type ParsedSource = {
70
+ sessions: Set<string>;
71
+ missingSession: boolean;
72
+ calls: Map<string, Call>;
73
+ duplicates: number;
74
+ unsupported: number;
75
+ };
76
+
77
+ function inspectTools(text: string, format: TaskFormat): ParsedSource {
78
+ const state: ParsedSource = { sessions: new Set(), missingSession: false, calls: new Map(), duplicates: 0, unsupported: 0 };
79
+ let codexSession: string | null = null;
80
+ const requests = new Map<string, string>();
81
+ const results = new Map<string, { result: string; failed: boolean; line: number; conflict: boolean; name?: string; namespace?: string }>();
82
+ const sessionFor = (row: Record<string, unknown>): string | null => {
83
+ const session = format === 'codex' ? codexSession : typeof row.sessionId === 'string' && row.sessionId.trim() ? row.sessionId : null;
84
+ if (session !== null) state.sessions.add(session);
85
+ return session;
86
+ };
87
+ const addCall = (session: string | null, id: unknown, name: unknown, args: unknown, line: number, namespace: string | null = null) => {
88
+ if (session === null) { state.missingSession = true; state.unsupported++; return; }
89
+ if (typeof id !== 'string' || !id || typeof name !== 'string' || !name) { state.unsupported++; return; }
90
+ let signature: string;
91
+ try { signature = canonical([session, namespace, name, args]); } catch { state.unsupported++; return; }
92
+ const callKey = canonical([session, id]);
93
+ const existing = state.calls.get(callKey);
94
+ if (existing) {
95
+ state.duplicates++;
96
+ if (existing.key !== signature) { existing.conflict = true; state.unsupported++; }
97
+ } else state.calls.set(callKey, { key: signature, name, namespace, category: category(name), line, conflict: false });
98
+ };
99
+ const addResult = (session: string | null, id: unknown, output: unknown, failed: boolean, line: number, name?: string, namespace?: string) => {
100
+ if (session === null) { state.missingSession = true; state.unsupported++; return; }
101
+ if (typeof id !== 'string' || !id || output === undefined) { state.unsupported++; return; }
102
+ let serialized: string;
103
+ try { serialized = canonical(output); } catch { state.unsupported++; return; }
104
+ const key = canonical([session, id]);
105
+ const existing = results.get(key);
106
+ if (existing && (existing.result !== serialized || existing.failed !== failed || existing.name !== name || existing.namespace !== namespace)) {
107
+ existing.conflict = true;
108
+ state.unsupported++;
109
+ } else if (!existing) results.set(key, { result: serialized, failed, line, conflict: false, name, namespace });
110
+ };
111
+ const lines = text.split('\n');
112
+ for (let i = 0; i < lines.length; i++) {
113
+ if (!lines[i]!.trim()) continue;
114
+ let row: unknown;
115
+ try { row = JSON.parse(lines[i]!); } catch { continue; }
116
+ if (!taskObject(row)) continue;
117
+ if (format === 'codex') {
118
+ if (!taskObject(row.payload)) continue;
119
+ const payload = row.payload;
120
+ if (row.type === 'session_meta') {
121
+ codexSession = typeof payload.id === 'string' && payload.id.trim() ? payload.id : null;
122
+ if (codexSession !== null) state.sessions.add(codexSession);
123
+ else state.missingSession = true;
124
+ }
125
+ if (row.type === 'event_msg' && payload.type === 'token_count' && codexSession === null) state.missingSession = true;
126
+ if (row.type !== 'response_item') continue;
127
+ if (payload.type === 'function_call') {
128
+ if ((payload.namespace !== undefined && payload.namespace !== null && typeof payload.namespace !== 'string') ||
129
+ (payload.encrypted_function_args !== undefined && payload.encrypted_function_args !== null)) { state.unsupported++; continue; }
130
+ let args: unknown;
131
+ try { if (typeof payload.arguments !== 'string') throw new Error(); args = JSON.parse(payload.arguments); }
132
+ catch { state.unsupported++; continue; }
133
+ addCall(codexSession, payload.call_id, payload.name, args, i + 1, typeof payload.namespace === 'string' ? payload.namespace : null);
134
+ } else if (payload.type === 'function_call_output') {
135
+ // Codex records textual output. Prose mentioning a failure is not an exit status.
136
+ if (typeof payload.output !== 'string' ||
137
+ (payload.namespace !== undefined && payload.namespace !== null && typeof payload.namespace !== 'string') ||
138
+ (payload.name !== undefined && payload.name !== null && typeof payload.name !== 'string')) { state.unsupported++; continue; }
139
+ addResult(codexSession, payload.call_id, payload.output, false, i + 1,
140
+ typeof payload.name === 'string' ? payload.name : undefined,
141
+ typeof payload.namespace === 'string' ? payload.namespace : undefined);
142
+ } else if (typeof payload.type === 'string' && /_call(?:_output)?$/u.test(payload.type)) {
143
+ state.unsupported++;
144
+ }
145
+ } else {
146
+ const session = sessionFor(row);
147
+ if (row.type !== 'assistant' && row.type !== 'user') continue;
148
+ if (session === null) state.missingSession = true;
149
+ if (row.type === 'assistant' && typeof row.requestId === 'string' && session !== null) {
150
+ const previous = requests.get(row.requestId);
151
+ if (previous !== undefined && previous !== session) throw new Error('Ambiguous Claude request identifiers across sessions. Supply separate session sources.');
152
+ requests.set(row.requestId, session);
153
+ }
154
+ if (!taskObject(row.message) || !Array.isArray(row.message.content)) continue;
155
+ for (const block of row.message.content) {
156
+ if (!taskObject(block)) continue;
157
+ if (row.type === 'assistant' && block.type === 'tool_use') addCall(session, block.id, block.name, block.input, i + 1);
158
+ if (row.type === 'user' && block.type === 'tool_result') {
159
+ if (block.is_error !== undefined && typeof block.is_error !== 'boolean') { state.unsupported++; continue; }
160
+ addResult(session, block.tool_use_id, block.content, block.is_error === true, i + 1);
161
+ }
162
+ }
163
+ }
164
+ }
165
+ for (const [key, call] of state.calls) {
166
+ const result = results.get(key);
167
+ if (result && ((result.name !== undefined && result.name !== call.name) || (result.namespace !== undefined && result.namespace !== call.namespace))) {
168
+ state.unsupported++;
169
+ continue;
170
+ }
171
+ if (result && result.line > call.line && !result.conflict && !call.conflict) {
172
+ call.result = result.result;
173
+ call.resultLine = result.line;
174
+ call.failed = result.failed;
175
+ }
176
+ }
177
+ for (const key of results.keys()) if (!state.calls.has(key)) state.unsupported++;
178
+ return state;
179
+ }
180
+
181
+ /** Analyze caller-supplied native transcripts in memory. No content is executed. */
182
+ export function analyzeTask(input: unknown): TaskReport {
183
+ const value = validateInput(input);
184
+ const report: TaskReport = {
185
+ version: 1, kind: 'trazum-task',
186
+ task: { id: value.taskId, type: value.taskType, criterion: value.criterion, policyId: value.policyId ?? 'baseline', outcome: value.outcome ?? 'unknown', assessor: value.assessor ?? null },
187
+ usage: {
188
+ records: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 0, apiEquivalentUsd: null, unpricedRecords: 0,
189
+ pricing: { source: 'bundled', lastReviewed: BUNDLED_CATALOGUE.lastReviewed, basis: 'api-equivalent' },
190
+ },
191
+ sources: [], coverage: { harnesses: [], models: [], gaps: [] },
192
+ tools: { calls: 0, duplicateCalls: 0, missingResults: 0, unsupported: 0, findings: [] },
193
+ limitations: [...TASK_LIMITATIONS],
194
+ };
195
+ const seenSessions = new Set<string>();
196
+ const seenSources = new Set<string>();
197
+ const missingByFormat = new Set<TaskFormat>();
198
+ const presentByFormat = new Set<TaskFormat>();
199
+ const models = new Set<string>();
200
+ const gaps = new Set<string>();
201
+ const usageLines: string[] = [];
202
+ for (let i = 0; i < value.sources.length; i++) {
203
+ const { format, text } = value.sources[i]!;
204
+ const inspected = inspectTools(text, format);
205
+ const sourceKey = fingerprint(`${format}:${text}`);
206
+ if (seenSources.has(sourceKey)) throw new Error('Duplicate task sources are not supported. Supply each session once.');
207
+ seenSources.add(sourceKey);
208
+ if (inspected.sessions.size === 0) inspected.missingSession = true;
209
+ if ((inspected.missingSession && presentByFormat.has(format)) || missingByFormat.has(format)) {
210
+ throw new Error('Multiple sources from the same harness require explicit, disjoint sessions.');
211
+ }
212
+ presentByFormat.add(format);
213
+ if (inspected.missingSession) { missingByFormat.add(format); gaps.add('missing-session'); }
214
+ const sessionKeys = [...inspected.sessions].map((session) => fingerprint(`${format}:${session}`)).sort();
215
+ for (const key of sessionKeys) {
216
+ if (seenSessions.has(key)) throw new Error('Overlapping task sessions are not supported. Supply each session once.');
217
+ seenSessions.add(key);
218
+ }
219
+ const conversion = format === 'claude-code' ? claudeCodeRecords(text) : codexRecords(text);
220
+ const { records, ...diagnostics } = conversion;
221
+ report.sources.push({ index: i + 1, format, fingerprint: sourceKey, sessionKeys, sessionCount: sessionKeys.length, diagnostics, completeness: 'not-established' });
222
+ if (conversion.unparseable) gaps.add('malformed-lines');
223
+ if ('unsupported' in conversion && (conversion.unsupported || conversion.missingModel)) gaps.add('incomplete-usage');
224
+ if ('assistantWithoutUsage' in conversion) {
225
+ if (conversion.assistantWithoutUsage) gaps.add('incomplete-usage');
226
+ if (conversion.disagreements) gaps.add('usage-disagreement');
227
+ if (conversion.noRequestId) gaps.add('missing-request-id');
228
+ }
229
+ if (!records.length) gaps.add('missing-usage');
230
+ for (const record of records) {
231
+ const line = JSON.stringify(record);
232
+ const parsed = parseUsageLine(line);
233
+ if (!parsed || ![parsed.inputTokens, parsed.outputTokens, parsed.cacheReadTokens, parsed.cacheWrite5mTokens, parsed.cacheWrite1hTokens].every((amount) => Number.isSafeInteger(amount) && amount >= 0)) {
234
+ gaps.add('incomplete-usage'); continue;
235
+ }
236
+ const model = BUNDLED_CATALOGUE.byId.get(parsed.model);
237
+ if (model) models.add(model.id);
238
+ else { gaps.add('unrecognized-model'); gaps.add('unpriced-model'); }
239
+ if (parsed.ts === null) gaps.add('missing-timestamp');
240
+ usageLines.push(line);
241
+ }
242
+ report.tools.calls += inspected.calls.size;
243
+ report.tools.duplicateCalls += inspected.duplicates;
244
+ report.tools.unsupported += inspected.unsupported;
245
+ const groups = new Map<string, Call[]>();
246
+ for (const call of inspected.calls.values()) {
247
+ if (call.result === undefined) { report.tools.missingResults++; continue; }
248
+ const key = canonical([call.key, call.result, call.failed]);
249
+ const group = groups.get(key) ?? [];
250
+ group.push(call); groups.set(key, group);
251
+ }
252
+ for (const group of groups.values()) {
253
+ if (group.length < 2) continue;
254
+ const first = group[0]!;
255
+ // Arbitrary tool names are never copied or assigned an optimization policy.
256
+ if (first.category === 'other') continue;
257
+ if (report.tools.findings.length >= 100) { gaps.add('findings-truncated'); continue; }
258
+ const finding: TaskFinding = {
259
+ kind: first.failed ? 'repeated-failure' : 'repeated-result', category: first.category,
260
+ count: group.length,
261
+ occurrences: group.slice(0, 20).map((call) => ({ source: i + 1, line: call.line, resultLine: call.resultLine! })),
262
+ };
263
+ if (group.length > 20) gaps.add('findings-truncated');
264
+ report.tools.findings.push(finding);
265
+ }
266
+ }
267
+ const profile = profileUsage(usageLines.join('\n'), { catalogue: BUNDLED_CATALOGUE });
268
+ for (const name of ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'] as const) {
269
+ report.usage[name] = profile.total[name] + profile.unpriced[name];
270
+ if (!Number.isSafeInteger(report.usage[name])) throw new Error('Task usage exceeds safe numeric limits.');
271
+ }
272
+ report.usage.totalTokens = report.usage.inputTokens + report.usage.outputTokens + report.usage.cacheReadTokens + report.usage.cacheWriteTokens;
273
+ if (!Number.isSafeInteger(report.usage.totalTokens)) throw new Error('Task usage exceeds safe numeric limits.');
274
+ report.usage.records = profile.total.calls + profile.unpriced.calls;
275
+ if (report.usage.records === 0) gaps.add('missing-usage');
276
+ report.usage.unpricedRecords = profile.unpriced.calls;
277
+ if (profile.total.assumedWriteTtlCalls) gaps.add('assumed-cache-ttl');
278
+ if (profile.skippedLines.length) gaps.add('incomplete-usage');
279
+ if (report.tools.missingResults || report.tools.unsupported) gaps.add('incomplete-tools');
280
+ if (report.usage.records && !report.usage.unpricedRecords && !gaps.has('assumed-cache-ttl')) report.usage.apiEquivalentUsd = profile.total.totalUsd;
281
+ report.coverage = { harnesses: [...presentByFormat].sort(), models: [...models].sort(), gaps: [...gaps].sort() };
282
+ return report;
283
+ }
@@ -0,0 +1,88 @@
1
+ export type TaskFormat = 'claude-code' | 'codex';
2
+ export type TaskOutcome = 'accepted' | 'rejected' | 'unknown';
3
+ export type TaskPolicyId = 'baseline' | 'repeat-review-v1';
4
+ export type TaskCategory = 'read' | 'search' | 'shell' | 'other';
5
+
6
+ export interface TaskInput {
7
+ taskId: string;
8
+ taskType: string;
9
+ criterion: string;
10
+ policyId?: TaskPolicyId;
11
+ outcome?: TaskOutcome;
12
+ assessor?: string;
13
+ sources: Array<{ format: TaskFormat; text: string }>;
14
+ }
15
+
16
+ export interface TaskFinding {
17
+ kind: 'repeated-result' | 'repeated-failure';
18
+ category: TaskCategory;
19
+ count: number;
20
+ occurrences: Array<{ source: number; line: number; resultLine: number }>;
21
+ }
22
+
23
+ export interface TaskReport {
24
+ version: 1;
25
+ kind: 'trazum-task';
26
+ task: {
27
+ id: string;
28
+ type: string;
29
+ criterion: string;
30
+ policyId: TaskPolicyId;
31
+ outcome: TaskOutcome;
32
+ assessor: string | null;
33
+ };
34
+ usage: {
35
+ records: number;
36
+ inputTokens: number;
37
+ outputTokens: number;
38
+ cacheReadTokens: number;
39
+ cacheWriteTokens: number;
40
+ totalTokens: number;
41
+ apiEquivalentUsd: number | null;
42
+ unpricedRecords: number;
43
+ pricing: { source: 'bundled'; lastReviewed: string; basis: 'api-equivalent' };
44
+ };
45
+ sources: Array<{
46
+ index: number;
47
+ format: TaskFormat;
48
+ /** Non-cryptographic reuse checks. These do not authenticate reports. */
49
+ fingerprint: string;
50
+ sessionKeys: string[];
51
+ sessionCount: number;
52
+ diagnostics: Record<string, number | { line: number; records: number }>;
53
+ completeness: 'not-established';
54
+ }>;
55
+ coverage: { harnesses: TaskFormat[]; models: string[]; gaps: string[] };
56
+ tools: {
57
+ calls: number;
58
+ duplicateCalls: number;
59
+ missingResults: number;
60
+ unsupported: number;
61
+ findings: TaskFinding[];
62
+ };
63
+ limitations: string[];
64
+ }
65
+
66
+ export interface TaskComparison {
67
+ version: 1;
68
+ kind: 'trazum-task-comparison';
69
+ verdict: 'lower-usage' | 'higher-usage' | 'similar-usage' | 'quality-regressed' | 'inconclusive';
70
+ reasons: string[];
71
+ tokenChange: { before: number; after: number; delta: number; percent: number | null } | null;
72
+ limitations: string[];
73
+ }
74
+
75
+ export const TASK_LIMITATIONS = [
76
+ 'Source completeness is not established. Only supplied records are measured.',
77
+ 'API-equivalent valuation is not an invoice, subscription charge or quota measurement.',
78
+ 'Identical tool calls and recorded results can be deliberate verification; repetition does not prove waste or unchanged external state.',
79
+ 'Outcomes, criteria and policy application are caller declarations, not independently verified quality or execution evidence.',
80
+ 'A paired observation is not a causal experiment. No monetary savings are inferred.',
81
+ 'Reuse fingerprints do not authenticate reports or guarantee anonymization.',
82
+ ] as const;
83
+
84
+ export const TASK_GAPS = [
85
+ 'missing-session', 'missing-usage', 'malformed-lines', 'incomplete-usage',
86
+ 'usage-disagreement', 'missing-request-id', 'unpriced-model', 'unrecognized-model',
87
+ 'missing-timestamp', 'assumed-cache-ttl', 'incomplete-tools', 'findings-truncated',
88
+ ] as const;
package/src/task.ts ADDED
@@ -0,0 +1,172 @@
1
+ import { analyzeTask, taskError, taskId, taskKeys, taskText } from './task-analysis.js';
2
+ import { MAX_INPUT_CHARS } from './limits.js';
3
+ import { BUNDLED_CATALOGUE } from './pricing.js';
4
+ import { TASK_GAPS, TASK_LIMITATIONS } from './task-types.js';
5
+ import type { TaskComparison, TaskReport } from './task-types.js';
6
+
7
+ export { analyzeTask };
8
+ export type { TaskCategory, TaskComparison, TaskFinding, TaskFormat, TaskInput, TaskOutcome, TaskPolicyId, TaskReport } from './task-types.js';
9
+
10
+ export interface TaskPolicy { id: 'repeat-review-v1'; instructions: string }
11
+
12
+ export const TASK_POLICY_INSTRUCTIONS = [
13
+ 'Before repeating a read or search with identical arguments, check whether the earlier result is still available and relevant.',
14
+ 'Reuse an earlier result only when you can establish that the underlying state has not changed. Otherwise read or search again.',
15
+ 'Before retrying an identical failed shell command, inspect the recorded failure and change the cause or explain why retrying is justified.',
16
+ 'Keep deliberate verification, fresh-state checks, required tests and safety checks. Never suppress failures or claim an outcome without evidence.',
17
+ 'This policy does not authorize running commands, changing permissions or omitting required work.',
18
+ ].join('\n');
19
+
20
+ const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
21
+ const checksum = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{16}$/u.test(value);
22
+ function exact(value: unknown, fields: readonly string[]): asserts value is Record<string, unknown> {
23
+ taskKeys(value, fields);
24
+ if (Object.keys(value).length !== fields.length) taskError();
25
+ }
26
+ function stringList(value: unknown, max: number): value is string[] {
27
+ return Array.isArray(value) && value.length <= max && value.every((item) => typeof item === 'string') && new Set(value).size === value.length;
28
+ }
29
+
30
+ /** Validate every persisted field; reports remain caller-supplied observations, not signed evidence. */
31
+ function validateReport(value: unknown): TaskReport {
32
+ exact(value, ['version', 'kind', 'task', 'usage', 'sources', 'coverage', 'tools', 'limitations']);
33
+ if (value.version !== 1 || value.kind !== 'trazum-task') taskError();
34
+ const task = value.task;
35
+ exact(task, ['id', 'type', 'criterion', 'policyId', 'outcome', 'assessor']);
36
+ if (!taskId(task.id) || !taskId(task.type) || !taskText(task.criterion, 500) ||
37
+ typeof task.policyId !== 'string' || !['baseline', 'repeat-review-v1'].includes(task.policyId) ||
38
+ typeof task.outcome !== 'string' || !['accepted', 'rejected', 'unknown'].includes(task.outcome) ||
39
+ (task.assessor !== null && !taskText(task.assessor, 100)) ||
40
+ (task.outcome !== 'unknown' && task.assessor === null)) taskError();
41
+ const usage = value.usage;
42
+ exact(usage, ['records', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'totalTokens', 'apiEquivalentUsd', 'unpricedRecords', 'pricing']);
43
+ exact(usage.pricing, ['source', 'lastReviewed', 'basis']);
44
+ if (usage.pricing.source !== 'bundled' || usage.pricing.basis !== 'api-equivalent' ||
45
+ typeof usage.pricing.lastReviewed !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(usage.pricing.lastReviewed) ||
46
+ !Number.isFinite(Date.parse(usage.pricing.lastReviewed)) ||
47
+ new Date(usage.pricing.lastReviewed).toISOString().slice(0, 10) !== usage.pricing.lastReviewed) taskError();
48
+ for (const key of ['records', 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'totalTokens', 'unpricedRecords']) if (!count(usage[key])) taskError();
49
+ if (usage.totalTokens !== (usage.inputTokens as number) + (usage.outputTokens as number) + (usage.cacheReadTokens as number) + (usage.cacheWriteTokens as number) ||
50
+ (usage.unpricedRecords as number) > (usage.records as number) ||
51
+ (usage.apiEquivalentUsd !== null && (typeof usage.apiEquivalentUsd !== 'number' || !Number.isFinite(usage.apiEquivalentUsd) || usage.apiEquivalentUsd < 0)) ||
52
+ ((usage.records === 0 || usage.unpricedRecords !== 0) && usage.apiEquivalentUsd !== null) ||
53
+ (usage.records === 0 && usage.totalTokens !== 0)) taskError();
54
+ if (!Array.isArray(value.sources) || value.sources.length < 1 || value.sources.length > 16) taskError();
55
+ const fingerprints = new Set<string>();
56
+ const sessions = new Set<string>();
57
+ const formats = new Set<string>();
58
+ const requiredGaps = new Set<string>();
59
+ let sourceIndex = 0;
60
+ for (const source of value.sources) {
61
+ exact(source, ['index', 'format', 'fingerprint', 'sessionKeys', 'sessionCount', 'diagnostics', 'completeness']);
62
+ if (source.index !== ++sourceIndex || typeof source.format !== 'string' || !['claude-code', 'codex'].includes(source.format) || !checksum(source.fingerprint) ||
63
+ !count(source.sessionCount) || !stringList(source.sessionKeys, 10_000) || !source.sessionKeys.every(checksum) || source.sessionKeys.length !== source.sessionCount ||
64
+ source.completeness !== 'not-established' || fingerprints.has(source.fingerprint)) taskError();
65
+ fingerprints.add(source.fingerprint);
66
+ formats.add(source.format as string);
67
+ for (const key of source.sessionKeys) { if (sessions.has(key)) taskError(); sessions.add(key); }
68
+ if (source.sessionCount === 0) requiredGaps.add('missing-session');
69
+ const diagnostics = source.diagnostics;
70
+ const names = source.format === 'claude-code'
71
+ ? ['collapsed', 'noRequestId', 'otherLines', 'unparseable', 'assistantWithoutUsage', 'streamed', 'disagreements', 'synthetic', 'resume']
72
+ : ['duplicates', 'unparseable', 'missingModel', 'unsupported', 'otherLines'];
73
+ exact(diagnostics, names);
74
+ for (const key of names) {
75
+ if (key === 'resume') {
76
+ exact(diagnostics.resume, ['line', 'records']);
77
+ if (!count(diagnostics.resume.line) || !count(diagnostics.resume.records)) taskError();
78
+ } else if (!count(diagnostics[key])) taskError();
79
+ }
80
+ if (diagnostics.unparseable) requiredGaps.add('malformed-lines');
81
+ if (diagnostics.assistantWithoutUsage || diagnostics.unsupported || diagnostics.missingModel) requiredGaps.add('incomplete-usage');
82
+ if (diagnostics.disagreements) requiredGaps.add('usage-disagreement');
83
+ if (diagnostics.noRequestId) requiredGaps.add('missing-request-id');
84
+ }
85
+ const coverage = value.coverage;
86
+ exact(coverage, ['harnesses', 'models', 'gaps']);
87
+ if (!stringList(coverage.harnesses, 2) || !stringList(coverage.models, BUNDLED_CATALOGUE.models.length) ||
88
+ !coverage.models.every((id) => BUNDLED_CATALOGUE.models.some((model) => model.id === id)) ||
89
+ !stringList(coverage.gaps, TASK_GAPS.length) || !coverage.gaps.every((gap) => (TASK_GAPS as readonly string[]).includes(gap)) ||
90
+ coverage.harnesses.slice().sort().join(',') !== [...formats].sort().join(',')) taskError();
91
+ if (usage.records === 0) requiredGaps.add('missing-usage');
92
+ if (usage.unpricedRecords !== 0) { requiredGaps.add('unpriced-model'); requiredGaps.add('unrecognized-model'); }
93
+ if ((usage.records as number) > (usage.unpricedRecords as number) && coverage.models.length === 0) taskError();
94
+ const tools = value.tools;
95
+ exact(tools, ['calls', 'duplicateCalls', 'missingResults', 'unsupported', 'findings']);
96
+ for (const key of ['calls', 'duplicateCalls', 'missingResults', 'unsupported']) if (!count(tools[key])) taskError();
97
+ if ((tools.missingResults as number) > (tools.calls as number) || !Array.isArray(tools.findings) || tools.findings.length > 100) taskError();
98
+ if (tools.missingResults || tools.unsupported) requiredGaps.add('incomplete-tools');
99
+ let findingsCalls = 0;
100
+ for (const finding of tools.findings) {
101
+ exact(finding, ['kind', 'category', 'count', 'occurrences']);
102
+ if (typeof finding.kind !== 'string' || !['repeated-result', 'repeated-failure'].includes(finding.kind) ||
103
+ typeof finding.category !== 'string' || !['read', 'search', 'shell'].includes(finding.category) ||
104
+ !count(finding.count) || finding.count < 2 || !Array.isArray(finding.occurrences) || finding.occurrences.length < 2 ||
105
+ finding.occurrences.length !== Math.min(finding.count, 20)) taskError();
106
+ findingsCalls += finding.count;
107
+ if (finding.count > 20) requiredGaps.add('findings-truncated');
108
+ let previousLine = 0;
109
+ let sourceIndexForFinding: number | null = null;
110
+ for (const occurrence of finding.occurrences) {
111
+ exact(occurrence, ['source', 'line', 'resultLine']);
112
+ if (!count(occurrence.source) || occurrence.source < 1 || occurrence.source > value.sources.length ||
113
+ !count(occurrence.line) || occurrence.line < 1 || occurrence.line < previousLine || !count(occurrence.resultLine) || occurrence.resultLine <= occurrence.line) taskError();
114
+ if (sourceIndexForFinding !== null && sourceIndexForFinding !== occurrence.source) taskError();
115
+ sourceIndexForFinding = occurrence.source;
116
+ previousLine = occurrence.line;
117
+ }
118
+ }
119
+ if (findingsCalls > (tools.calls as number) - (tools.missingResults as number)) taskError();
120
+ const gaps = coverage.gaps as string[];
121
+ if ([...requiredGaps].some((gap) => !gaps.includes(gap))) taskError();
122
+ if (!Array.isArray(value.limitations) || JSON.stringify(value.limitations) !== JSON.stringify(TASK_LIMITATIONS)) taskError();
123
+ return value as unknown as TaskReport;
124
+ }
125
+
126
+ export function parseTaskReport(text: string): TaskReport {
127
+ if (typeof text !== 'string' || text.length > MAX_INPUT_CHARS) taskError();
128
+ let value: unknown;
129
+ try { value = JSON.parse(text); } catch { taskError(); }
130
+ return validateReport(value);
131
+ }
132
+
133
+ function validated(value: TaskReport): TaskReport {
134
+ let text: string;
135
+ try { text = JSON.stringify(value); } catch { taskError(); }
136
+ return parseTaskReport(text);
137
+ }
138
+
139
+ export function taskPolicy(report: TaskReport): TaskPolicy {
140
+ const checked = validated(report);
141
+ if (!checked.tools.findings.some((finding) => finding.category === 'read' || finding.category === 'search' || finding.kind === 'repeated-failure')) {
142
+ throw new Error('No actionable repeated read, search or explicit failure evidence was found.');
143
+ }
144
+ return { id: 'repeat-review-v1', instructions: TASK_POLICY_INSTRUCTIONS };
145
+ }
146
+
147
+ /** Compare declared matched tasks; never infer causality, quality or monetary savings. */
148
+ export function compareTasks(before: TaskReport, after: TaskReport): TaskComparison {
149
+ const a = validated(before);
150
+ const b = validated(after);
151
+ const result: TaskComparison = { version: 1, kind: 'trazum-task-comparison', verdict: 'inconclusive', reasons: [], tokenChange: null, limitations: [...TASK_LIMITATIONS] };
152
+ if (a.task.type !== b.task.type) result.reasons.push('task-type-mismatch');
153
+ if (a.task.criterion !== b.task.criterion) result.reasons.push('criterion-mismatch');
154
+ if (a.task.policyId !== 'baseline' || b.task.policyId !== 'repeat-review-v1') result.reasons.push('policy-pair-mismatch');
155
+ if (a.coverage.harnesses.slice().sort().join(',') !== b.coverage.harnesses.slice().sort().join(',')) result.reasons.push('harness-coverage-mismatch');
156
+ if (a.coverage.models.slice().sort().join(',') !== b.coverage.models.slice().sort().join(',')) result.reasons.push('model-coverage-mismatch');
157
+ const fingerprints = new Set(a.sources.map((source) => source.fingerprint));
158
+ const sessions = new Set(a.sources.flatMap((source) => source.sessionKeys));
159
+ if (b.sources.some((source) => fingerprints.has(source.fingerprint) || source.sessionKeys.some((key) => sessions.has(key)))) result.reasons.push('source-reuse');
160
+ if (a.coverage.gaps.length || b.coverage.gaps.length) result.reasons.push('incomplete-evidence');
161
+ if (result.reasons.length) return result;
162
+ if (a.task.outcome === 'accepted' && b.task.outcome === 'rejected') {
163
+ result.verdict = 'quality-regressed'; result.reasons.push('declared-acceptance-regressed'); return result;
164
+ }
165
+ if (a.task.outcome !== 'accepted' || b.task.outcome !== 'accepted') { result.reasons.push('accepted-outcomes-required'); return result; }
166
+ if (a.usage.records === 0 || b.usage.records === 0 || a.usage.totalTokens === 0) { result.reasons.push('nonzero-baseline-required'); return result; }
167
+ const delta = b.usage.totalTokens - a.usage.totalTokens;
168
+ result.tokenChange = { before: a.usage.totalTokens, after: b.usage.totalTokens, delta, percent: delta / a.usage.totalTokens * 100 };
169
+ result.verdict = delta < 0 ? 'lower-usage' : delta > 0 ? 'higher-usage' : 'similar-usage';
170
+ result.reasons.push('paired-observation-not-causal');
171
+ return result;
172
+ }