@openpond/evals 0.10.7 → 0.10.9
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/LEARNING.md +26 -0
- package/dist/learning/admission.js +4 -0
- package/dist/learning/authoring-service.js +11 -1
- package/dist/learning/authoring.js +1 -0
- package/dist/learning/contracts.js +28 -1
- package/dist/learning/index.js +3 -0
- package/dist/learning/intake-contracts.js +30 -0
- package/dist/learning/intake-csv.js +59 -0
- package/dist/learning/intake-history.js +86 -0
- package/dist/learning/intake-service.js +79 -0
- package/dist/learning/intake.js +112 -0
- package/dist/learning/operations.js +6 -1
- package/dist/learning/rating-reward-fixture.js +19 -0
- package/dist/learning/service.js +11 -2
- package/dist/learning/transport.js +1 -1
- package/dist/rewards.js +6 -4
- package/dist/types/learning/admission.d.ts +1 -0
- package/dist/types/learning/admission.d.ts.map +1 -1
- package/dist/types/learning/authoring-service.d.ts +11 -0
- package/dist/types/learning/authoring-service.d.ts.map +1 -1
- package/dist/types/learning/authoring.d.ts +55 -0
- package/dist/types/learning/authoring.d.ts.map +1 -1
- package/dist/types/learning/batch-service.d.ts +1 -0
- package/dist/types/learning/batch-service.d.ts.map +1 -1
- package/dist/types/learning/contracts.d.ts +34 -0
- package/dist/types/learning/contracts.d.ts.map +1 -1
- package/dist/types/learning/index.d.ts +3 -0
- package/dist/types/learning/index.d.ts.map +1 -1
- package/dist/types/learning/intake-contracts.d.ts +87 -0
- package/dist/types/learning/intake-contracts.d.ts.map +1 -0
- package/dist/types/learning/intake-csv.d.ts +3 -0
- package/dist/types/learning/intake-csv.d.ts.map +1 -0
- package/dist/types/learning/intake-history.d.ts +5 -0
- package/dist/types/learning/intake-history.d.ts.map +1 -0
- package/dist/types/learning/intake-service.d.ts +8 -0
- package/dist/types/learning/intake-service.d.ts.map +1 -0
- package/dist/types/learning/intake.d.ts +6 -0
- package/dist/types/learning/intake.d.ts.map +1 -0
- package/dist/types/learning/operations.d.ts +61 -0
- package/dist/types/learning/operations.d.ts.map +1 -1
- package/dist/types/learning/rating-reward-fixture.d.ts +8 -0
- package/dist/types/learning/rating-reward-fixture.d.ts.map +1 -0
- package/dist/types/learning/repository.d.ts +22 -0
- package/dist/types/learning/repository.d.ts.map +1 -1
- package/dist/types/learning/service.d.ts.map +1 -1
- package/dist/types/learning/transport.d.ts +55 -0
- package/dist/types/learning/transport.d.ts.map +1 -1
- package/dist/types/rewards.d.ts.map +1 -1
- package/package.json +1 -1
- package/schemas/learning/v1/binding.schema.json +0 -1
- package/schemas/learning/v1/command-request.schema.json +441 -303
- package/schemas/learning/v1/decision.schema.json +0 -1
- package/schemas/learning/v1/definition.schema.json +19 -7
- package/schemas/learning/v1/draft.schema.json +31 -0
- package/schemas/learning/v1/feedback-submission.schema.json +55 -37
- package/schemas/learning/v1/feedback.schema.json +94 -38
- package/schemas/learning/v1/grade.schema.json +0 -1
- package/schemas/learning/v1/read-request.schema.json +7 -0
package/LEARNING.md
CHANGED
|
@@ -28,6 +28,32 @@ and approval operations still validate their authoritative inputs independently.
|
|
|
28
28
|
|
|
29
29
|
## Data flow
|
|
30
30
|
|
|
31
|
+
### File and agent-history intake
|
|
32
|
+
|
|
33
|
+
`previewTaskIntake({ format, files })` validates JSON, JSONL, CSV, Hermes native
|
|
34
|
+
session JSONL, or an OpenClaw trajectory folder. Each file has a relative `path`
|
|
35
|
+
and its UTF-8 `text`. Previews report invalid rows separately and retain stable
|
|
36
|
+
source, attempt, family and split identities. Treat imported labels as source
|
|
37
|
+
metadata until a reviewer creates authenticated feedback.
|
|
38
|
+
|
|
39
|
+
For recorded attempts, submit `import_intake` with the same files and format,
|
|
40
|
+
`expectedPreviewHash`, a collection `name`, and up to 90 selected `recordIds`.
|
|
41
|
+
The owner reparses the files, verifies the preview hash, retains source text in
|
|
42
|
+
private assets and deduplicates retries. Source-producer credentials cannot use
|
|
43
|
+
this workspace import operation. Inputs are limited to 100 files, 5 MiB and
|
|
44
|
+
1,000 preview records; callers can submit selection chunks with stable operation
|
|
45
|
+
IDs. Histories remain in Labeling with unresolved context requirements, and an
|
|
46
|
+
empty Reward binding reports `not_configured`. They cannot be admitted or sealed
|
|
47
|
+
for training until their context and Reward configuration are resolved.
|
|
48
|
+
|
|
49
|
+
Plain task records can be added to a draft with
|
|
50
|
+
`appendTaskIntake(draft, preview, recordIds)` from `openpond-sdk/taskset-drafts`.
|
|
51
|
+
This preserves private references and source metadata, rejects attempts and
|
|
52
|
+
unresolved histories, and rejects cross-split family or identical-input overlap.
|
|
53
|
+
Repeating identical tasks is idempotent; imports never overwrite edited tasks.
|
|
54
|
+
|
|
55
|
+
### Reviewed task lifecycle
|
|
56
|
+
|
|
31
57
|
1. Publish a Reward, then a binding, task definition and source. Use
|
|
32
58
|
`publish_resources` to publish dependent resources atomically. Pin an existing
|
|
33
59
|
release by `{ id, revision, contentHash }`; edits create the next revision with
|
|
@@ -19,6 +19,8 @@ export function inspectTaskEvidence(evidence, definition) {
|
|
|
19
19
|
issues.push(...expected.issues.map((issue) => ({ ...issue, path: `/expected${issue.path}` })));
|
|
20
20
|
}
|
|
21
21
|
const evidenceValidity = issues.length ? "invalid" : "valid";
|
|
22
|
+
for (const requirement of definition.contextRequirements ?? [])
|
|
23
|
+
issues.push({ path: "/taskDefinition/contextRequirements", code: "context_required", message: requirement });
|
|
22
24
|
if (!example.familyKey)
|
|
23
25
|
issues.push({ path: "/familyKey", code: "family_unresolved", message: "Resolve the source family before admitting this task." });
|
|
24
26
|
return { evidenceValidity, taskReady: issues.length === 0, observedOutputValid: example.observedOutput === null ? null : validateTaskValue(definition.outputSchema, example.observedOutput).valid, issues };
|
|
@@ -133,6 +135,8 @@ export function taskFamilyReservations(evidence, definition) {
|
|
|
133
135
|
export function sealTaskBatch(input) {
|
|
134
136
|
const definition = TaskDefinitionSchema.parse(input.definition);
|
|
135
137
|
assertLearningContentHash(definition);
|
|
138
|
+
if (definition.contextRequirements?.length)
|
|
139
|
+
throw new LearningDomainError("task_context_not_configured", 422, definition.contextRequirements.join(" "));
|
|
136
140
|
if (!sameLearningRef(definition.rewardBinding, learningRef(input.binding)))
|
|
137
141
|
throw new LearningDomainError("task_definition_reward_binding_mismatch", 422);
|
|
138
142
|
resolveBoundRewards(input.binding, input.rewards);
|
|
@@ -2,7 +2,7 @@ import { assertBoundedTaskJson } from "../task-schema.js";
|
|
|
2
2
|
import { AuthoringDraftSchema } from "./authoring.js";
|
|
3
3
|
import { LearningDomainError } from "./errors.js";
|
|
4
4
|
import { learningRef, sameLearningRef, sealLearningContent } from "./contracts.js";
|
|
5
|
-
import { requireLearningRelease } from "./repository.js";
|
|
5
|
+
import { requireLearningRelease, requireLearningResource } from "./repository.js";
|
|
6
6
|
export async function saveAuthoringDraft(tx, input, now) {
|
|
7
7
|
// A 100-record page remains below the common 16 MiB response limit.
|
|
8
8
|
assertBoundedTaskJson(input.draft, 131_072);
|
|
@@ -14,6 +14,16 @@ export async function saveAuthoringDraft(tx, input, now) {
|
|
|
14
14
|
throw new LearningDomainError("authoring_draft_base_mismatch", 422);
|
|
15
15
|
await requireLearningRelease(tx, input.draft.targetKind, input.draft.baseRelease);
|
|
16
16
|
}
|
|
17
|
+
if (input.draft.targetKind === "reward")
|
|
18
|
+
for (const fixture of input.draft.fields.fixtures ?? []) {
|
|
19
|
+
if (!fixture.sourceLabel)
|
|
20
|
+
continue;
|
|
21
|
+
const { evidence, feedback } = fixture.sourceLabel;
|
|
22
|
+
await requireLearningRelease(tx, "evidence", evidence);
|
|
23
|
+
const label = await requireLearningResource(tx, "feedback", feedback.id, feedback.revision);
|
|
24
|
+
if (!label.evidence || !sameLearningRef(label.evidence, evidence))
|
|
25
|
+
throw new LearningDomainError("reward_fixture_label_mismatch", 422);
|
|
26
|
+
}
|
|
17
27
|
const draft = AuthoringDraftSchema.parse(sealLearningContent({ ...input.draft, schemaVersion: "openpond.authoringDraft.v1", revision: input.expectedRevision + 1, status: "draft", publishedRelease: null, createdAt: previous?.createdAt ?? now, updatedAt: now }));
|
|
18
28
|
await tx.put("draft", draft, input.expectedRevision, { parentId: draft.targetKind, status: draft.status });
|
|
19
29
|
return { kind: "draft", id: draft.id, revision: draft.revision };
|
|
@@ -10,6 +10,7 @@ export const RewardFixtureAuthoringFieldsSchema = z.object({
|
|
|
10
10
|
infrastructureError: z.string().max(20_000),
|
|
11
11
|
expectedStatus: z.enum(["scored", "pending", "unavailable", "failed"]),
|
|
12
12
|
minimumScore: z.string(), maximumScore: z.string(), expectedPassed: z.enum(["true", "false", "any"]),
|
|
13
|
+
sourceLabel: z.object({ evidence: LearningRevisionRefSchema, feedback: z.object({ id: ReleaseIdSchema, revision: z.number().int().positive() }).strict() }).strict().optional(),
|
|
13
14
|
}).strict();
|
|
14
15
|
export const RewardAuthoringFieldsSchema = z.object({
|
|
15
16
|
name: z.string().max(500), description: z.string().max(10_000),
|
|
@@ -19,6 +19,7 @@ export const TaskDefinitionContentSchema = z.object({
|
|
|
19
19
|
inputSchema: z.record(z.string(), z.unknown()),
|
|
20
20
|
outputSchema: z.record(z.string(), z.unknown()),
|
|
21
21
|
requiredOutputs: TaskRecordSchema.shape.requiredOutputs,
|
|
22
|
+
contextRequirements: z.array(z.string().trim().min(1).max(2_000)).max(100).optional(),
|
|
22
23
|
rewardBinding: LearningRevisionRefSchema,
|
|
23
24
|
harness: ImmutableReleaseRefSchema.nullable(),
|
|
24
25
|
execution: TasksetReleaseContentSchema.pick({ policy: true, environment: true, environmentRelease: true, tools: true, capabilities: true, verifierSetRelease: true }).strict(),
|
|
@@ -105,6 +106,20 @@ export const TaskEvidenceContentSchema = z.object({
|
|
|
105
106
|
receivedAt: ReleaseTimestampSchema,
|
|
106
107
|
}).strict();
|
|
107
108
|
export const TaskEvidenceSchema = TaskEvidenceContentSchema.extend({ contentHash: ReleaseHashSchema }).strict();
|
|
109
|
+
/** A retained judgment of this exact attempt, separate from task admission. */
|
|
110
|
+
export const TaskRatingSchema = z.object({
|
|
111
|
+
schemaVersion: z.literal("openpond.taskRating.v1"),
|
|
112
|
+
criteria: z.string().trim().min(1).max(20_000),
|
|
113
|
+
scale: z.object({ minimum: z.number().finite(), maximum: z.number().finite() }).strict(),
|
|
114
|
+
score: z.number().finite(),
|
|
115
|
+
evidence: z.string().max(20_000),
|
|
116
|
+
explanation: z.string().max(20_000),
|
|
117
|
+
}).strict().superRefine((rating, context) => {
|
|
118
|
+
if (rating.scale.minimum >= rating.scale.maximum)
|
|
119
|
+
context.addIssue({ code: "custom", path: ["scale"], message: "The score scale must have an increasing range." });
|
|
120
|
+
if (rating.score < rating.scale.minimum || rating.score > rating.scale.maximum)
|
|
121
|
+
context.addIssue({ code: "custom", path: ["score"], message: "The score must be within its declared scale." });
|
|
122
|
+
});
|
|
108
123
|
export const TaskFeedbackSubmissionSchema = z.object({
|
|
109
124
|
schemaVersion: z.literal("openpond.taskFeedback.v1"),
|
|
110
125
|
sourceId: ReleaseIdSchema,
|
|
@@ -116,7 +131,18 @@ export const TaskFeedbackSubmissionSchema = z.object({
|
|
|
116
131
|
kind: z.enum(["outcome", "target_correction", "ground_truth_correction", "input_correction", "family_resolution"]),
|
|
117
132
|
value: LearningJsonObjectSchema,
|
|
118
133
|
note: z.string().max(20_000),
|
|
119
|
-
}).strict()
|
|
134
|
+
}).strict().superRefine((submission, context) => {
|
|
135
|
+
if (submission.value.schemaVersion !== "openpond.taskRating.v1")
|
|
136
|
+
return;
|
|
137
|
+
if (submission.expectedEvidenceHash === null)
|
|
138
|
+
context.addIssue({ code: "custom", path: ["expectedEvidenceHash"], message: "A rating must identify the exact evidence revision." });
|
|
139
|
+
if (submission.kind !== "outcome")
|
|
140
|
+
context.addIssue({ code: "custom", path: ["kind"], message: "Ratings must be submitted as outcomes." });
|
|
141
|
+
const rating = TaskRatingSchema.safeParse(submission.value);
|
|
142
|
+
if (!rating.success)
|
|
143
|
+
for (const issue of rating.error.issues)
|
|
144
|
+
context.addIssue({ code: "custom", path: ["value", ...issue.path], message: issue.message });
|
|
145
|
+
});
|
|
120
146
|
export const TaskFeedbackSchema = z.object({
|
|
121
147
|
schemaVersion: z.literal("openpond.taskFeedbackRecord.v1"),
|
|
122
148
|
id: ReleaseIdSchema,
|
|
@@ -125,6 +151,7 @@ export const TaskFeedbackSchema = z.object({
|
|
|
125
151
|
evidence: LearningRevisionRefSchema.nullable(),
|
|
126
152
|
createdAt: ReleaseTimestampSchema,
|
|
127
153
|
revision: z.number().int().positive(),
|
|
154
|
+
submittedBy: z.object({ id: ReleaseIdSchema, role: z.enum(["editor", "reviewer", "source"]), sourceId: ReleaseIdSchema.nullable() }).strict().nullable().default(null),
|
|
128
155
|
review: z.object({ actorId: ReleaseIdSchema, decision: LearningRevisionRefSchema.nullable(), note: z.string().max(20_000), resolvedAt: ReleaseTimestampSchema }).strict().nullable().default(null),
|
|
129
156
|
}).strict();
|
|
130
157
|
export const TaskAdmissionDecisionContentSchema = z.object({
|
package/dist/learning/index.js
CHANGED
|
@@ -9,6 +9,9 @@ export * from "./transport.js";
|
|
|
9
9
|
export * from "./errors.js";
|
|
10
10
|
export * from "./authoring.js";
|
|
11
11
|
export * from "./reward-authoring.js";
|
|
12
|
+
export * from "./rating-reward-fixture.js";
|
|
13
|
+
export * from "./intake-contracts.js";
|
|
14
|
+
export * from "./intake.js";
|
|
12
15
|
export * from "./reward-checks.js";
|
|
13
16
|
export * from "./reward-check-worker.js";
|
|
14
17
|
export * from "./reward-fixture-executor.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { contentHash } from "@openpond/harness";
|
|
3
|
+
import { LearningJsonObjectSchema } from "./contracts.js";
|
|
4
|
+
import { TaskSplitSchema } from "../tasksets.js";
|
|
5
|
+
export const TASK_INTAKE_LIMITS = { bytes: 5 * 1024 * 1024, records: 1_000, files: 100, messages: 2_000 };
|
|
6
|
+
export const TaskIntakeFormatSchema = z.enum(["json", "jsonl", "csv", "hermes", "openclaw"]);
|
|
7
|
+
export const TaskIntakeFileSchema = z.object({ path: z.string().min(1).max(500), text: z.string() }).strict();
|
|
8
|
+
export const TaskIntakeRecordSchema = z.object({
|
|
9
|
+
id: z.string().min(1).max(200), familyKey: z.string().min(1).max(200), split: TaskSplitSchema,
|
|
10
|
+
kind: z.enum(["task", "attempt"]), input: LearningJsonObjectSchema,
|
|
11
|
+
observedOutput: LearningJsonObjectSchema.nullable(), expected: LearningJsonObjectSchema.nullable(),
|
|
12
|
+
sourceId: z.string().min(1).max(2_000), sourceHash: z.string().length(64),
|
|
13
|
+
occurredAt: z.string().datetime().nullable(),
|
|
14
|
+
// Imported labels and metadata are retained evidence, never admissions or
|
|
15
|
+
// executable Rewards. Hosts store these outside policy-visible fields.
|
|
16
|
+
metadata: LearningJsonObjectSchema, warnings: z.array(z.string().max(2_000)).max(100),
|
|
17
|
+
needsContext: z.boolean(),
|
|
18
|
+
}).strict();
|
|
19
|
+
export const TaskIntakePreviewSchema = z.object({
|
|
20
|
+
schemaVersion: z.literal("openpond.taskIntakePreview.v1"), format: TaskIntakeFormatSchema,
|
|
21
|
+
contentHash: z.string().length(64), records: z.array(TaskIntakeRecordSchema).max(TASK_INTAKE_LIMITS.records),
|
|
22
|
+
issues: z.array(z.object({ file: z.string(), row: z.number().int().positive().nullable(), message: z.string() }).strict()).max(1_000),
|
|
23
|
+
}).strict();
|
|
24
|
+
export function intakeId(source, identity) { return `${source}-${contentHash(identity)}`; }
|
|
25
|
+
export function intakeDate(value) {
|
|
26
|
+
if (typeof value !== "string" && typeof value !== "number")
|
|
27
|
+
return null;
|
|
28
|
+
const date = new Date(typeof value === "number" ? value * 1_000 : value);
|
|
29
|
+
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
|
30
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { TASK_INTAKE_LIMITS } from "./intake-contracts.js";
|
|
2
|
+
/** RFC 4180-style quoting; newlines inside a quoted field remain content. */
|
|
3
|
+
export function parseTaskIntakeCsv(text) {
|
|
4
|
+
const rows = [];
|
|
5
|
+
let row = [], field = "", quoted = false, closed = false;
|
|
6
|
+
const finishField = () => { row.push(field); field = ""; closed = false; };
|
|
7
|
+
const finishRow = () => {
|
|
8
|
+
finishField();
|
|
9
|
+
if (row.some(value => value.length))
|
|
10
|
+
rows.push(row);
|
|
11
|
+
row = [];
|
|
12
|
+
if (rows.length > TASK_INTAKE_LIMITS.records + 1)
|
|
13
|
+
throw new Error("CSV exceeds the 1,000-record limit.");
|
|
14
|
+
};
|
|
15
|
+
for (let index = 0; index < text.length; index++) {
|
|
16
|
+
const char = text[index];
|
|
17
|
+
if (quoted) {
|
|
18
|
+
if (char === '"' && text[index + 1] === '"') {
|
|
19
|
+
field += '"';
|
|
20
|
+
index++;
|
|
21
|
+
}
|
|
22
|
+
else if (char === '"') {
|
|
23
|
+
quoted = false;
|
|
24
|
+
closed = true;
|
|
25
|
+
}
|
|
26
|
+
else
|
|
27
|
+
field += char;
|
|
28
|
+
}
|
|
29
|
+
else if (char === ",")
|
|
30
|
+
finishField();
|
|
31
|
+
else if (char === "\n" || char === "\r") {
|
|
32
|
+
if (char === "\r" && text[index + 1] === "\n")
|
|
33
|
+
index++;
|
|
34
|
+
finishRow();
|
|
35
|
+
}
|
|
36
|
+
else if (char === '"' && !field && !closed)
|
|
37
|
+
quoted = true;
|
|
38
|
+
else {
|
|
39
|
+
if (closed || char === '"')
|
|
40
|
+
throw new Error("CSV has an invalid quoted field.");
|
|
41
|
+
field += char;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (quoted)
|
|
45
|
+
throw new Error("CSV has an unterminated quoted field.");
|
|
46
|
+
if (field || row.length || closed)
|
|
47
|
+
finishRow();
|
|
48
|
+
const header = rows.shift()?.map(value => value.trim().replace(/^\uFEFF/u, ""));
|
|
49
|
+
if (!header?.includes("instruction"))
|
|
50
|
+
throw new Error("CSV requires an instruction column.");
|
|
51
|
+
const allowed = new Set(["instruction", "context", "reference", "labels", "id", "familyKey", "split"]);
|
|
52
|
+
if (header.some(value => !allowed.has(value)) || new Set(header).size !== header.length)
|
|
53
|
+
throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");
|
|
54
|
+
return rows.map((values, index) => {
|
|
55
|
+
if (values.length !== header.length)
|
|
56
|
+
throw new Error(`CSV record ${index + 2} has a different number of columns from its header.`);
|
|
57
|
+
return Object.fromEntries(header.map((name, column) => [name, values[column]]).filter(([, value]) => value !== ""));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { contentHash } from "@openpond/harness";
|
|
3
|
+
import { assertBoundedTaskJson } from "../task-schema.js";
|
|
4
|
+
import { LearningJsonObjectSchema } from "./contracts.js";
|
|
5
|
+
import { intakeDate, intakeId, TASK_INTAKE_LIMITS, TaskIntakeRecordSchema } from "./intake-contracts.js";
|
|
6
|
+
const messageSchema = z.object({ role: z.string().min(1), content: z.json().nullable().optional() }).catchall(z.json());
|
|
7
|
+
const hermesSchema = z.object({ id: z.string().min(1), messages: z.array(messageSchema).min(1).max(TASK_INTAKE_LIMITS.messages),
|
|
8
|
+
lineage_session_ids: z.array(z.string()).optional(), parent_session_id: z.string().nullable().optional() }).catchall(z.json());
|
|
9
|
+
export function parseHermesSession(value) {
|
|
10
|
+
const session = hermesSchema.parse(value);
|
|
11
|
+
const family = session.lineage_session_ids?.[0] ?? session.parent_session_id ?? session.id;
|
|
12
|
+
const { messages: _messages, segments: _segments, ...metadata } = session;
|
|
13
|
+
return historyRecords("hermes", session.id, family, session.messages, {
|
|
14
|
+
sourceHash: contentHash(value), metadata: { session: metadata },
|
|
15
|
+
warnings: ["Imported session context and tools need review before this can become an executable task."],
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
const manifestSchema = z.object({ traceSchema: z.literal("openclaw-trajectory"), schemaVersion: z.literal(1),
|
|
19
|
+
traceId: z.string().min(1), sessionId: z.string().min(1), leafId: z.string().nullable(),
|
|
20
|
+
eventCount: z.number().int().nonnegative(), warnings: z.array(LearningJsonObjectSchema).optional() }).catchall(z.json());
|
|
21
|
+
const eventSchema = z.object({ traceSchema: z.literal("openclaw-trajectory"), schemaVersion: z.literal(1),
|
|
22
|
+
traceId: z.string(), sessionId: z.string(), seq: z.number().int().nonnegative(), type: z.string(), ts: z.string() }).catchall(z.json());
|
|
23
|
+
const branchSchema = z.object({ header: LearningJsonObjectSchema.nullable(), leafId: z.string().nullable(),
|
|
24
|
+
entries: z.array(z.object({ id: z.string().min(1), type: z.string().min(1), parentId: z.string().nullable().optional(),
|
|
25
|
+
message: messageSchema.optional() }).catchall(z.json())).max(TASK_INTAKE_LIMITS.messages) }).strict();
|
|
26
|
+
/** Takes named bundle files; never extracts paths or runs uploaded code. */
|
|
27
|
+
export function parseOpenClawBundle(files) {
|
|
28
|
+
const read = (path) => {
|
|
29
|
+
const file = files.find(file => file.path === path);
|
|
30
|
+
if (!file)
|
|
31
|
+
throw new Error(`OpenClaw bundle is missing ${path}.`);
|
|
32
|
+
return file.text;
|
|
33
|
+
};
|
|
34
|
+
const manifest = manifestSchema.parse(JSON.parse(read("manifest.json")));
|
|
35
|
+
const branch = branchSchema.parse(JSON.parse(read("session-branch.json")));
|
|
36
|
+
if (branch.leafId !== manifest.leafId)
|
|
37
|
+
throw new Error("OpenClaw manifest and session branch identify different leaves.");
|
|
38
|
+
const events = read("events.jsonl").split(/\r?\n/u).filter(line => line.trim()).map(line => eventSchema.parse(JSON.parse(line)));
|
|
39
|
+
if (events.length !== manifest.eventCount || events.some(event => event.traceId !== manifest.traceId || event.sessionId !== manifest.sessionId))
|
|
40
|
+
throw new Error("OpenClaw events do not match the manifest identity or count.");
|
|
41
|
+
if (branch.header && branch.header.id !== manifest.sessionId)
|
|
42
|
+
throw new Error("OpenClaw session header does not match the manifest.");
|
|
43
|
+
const ids = new Set();
|
|
44
|
+
for (const [index, entry] of branch.entries.entries()) {
|
|
45
|
+
if (ids.has(entry.id))
|
|
46
|
+
throw new Error("OpenClaw branch contains duplicate entry IDs.");
|
|
47
|
+
if (index && entry.parentId !== branch.entries[index - 1].id)
|
|
48
|
+
throw new Error("OpenClaw branch is incomplete or out of order.");
|
|
49
|
+
ids.add(entry.id);
|
|
50
|
+
}
|
|
51
|
+
if (branch.entries.length && branch.entries.at(-1).id !== branch.leafId)
|
|
52
|
+
throw new Error("OpenClaw branch does not reach its declared leaf.");
|
|
53
|
+
const messages = branch.entries.filter(entry => entry.type === "message" && entry.message).map(entry => ({ ...entry.message, entryId: entry.id,
|
|
54
|
+
timestamp: typeof entry.timestamp === "string" ? entry.timestamp : typeof entry.message.timestamp === "number" ? new Date(entry.message.timestamp).toISOString() : null }));
|
|
55
|
+
return historyRecords("openclaw", manifest.sessionId, manifest.sessionId, messages, {
|
|
56
|
+
sourceHash: contentHash(files), metadata: { manifest, sourceFiles: files.map(file => file.path) },
|
|
57
|
+
warnings: ["Imported trajectory context and tools need review before this can become an executable task.",
|
|
58
|
+
...(manifest.warnings ?? []).map(warning => typeof warning.message === "string" ? warning.message.slice(0, 2_000) : "The source exporter reported incomplete context.")],
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function historyRecords(format, sessionId, family, messages, source) {
|
|
62
|
+
const starts = messages.flatMap((message, index) => message.role === "user" ? [index] : []);
|
|
63
|
+
if (!starts.length)
|
|
64
|
+
throw new Error("This history contains no user request. Supply a session with its request context.");
|
|
65
|
+
let normalizedBytes = 0;
|
|
66
|
+
return starts.map((start, position) => {
|
|
67
|
+
const end = starts[position + 1] ?? messages.length;
|
|
68
|
+
const responses = messages.slice(start + 1, end);
|
|
69
|
+
const assistant = responses.filter(message => message.role === "assistant").at(-1);
|
|
70
|
+
const request = messages[start];
|
|
71
|
+
const identity = request.entryId ?? request.message_id ?? request.id ?? contentHash({ start, request });
|
|
72
|
+
const record = {
|
|
73
|
+
id: intakeId(format, [sessionId, identity]), familyKey: intakeId(format, family), split: "train", kind: "attempt",
|
|
74
|
+
input: { request: request.content ?? null, messages: messages.slice(0, start + 1) },
|
|
75
|
+
observedOutput: assistant ? { response: assistant.content ?? null, messages: responses } : null, expected: null,
|
|
76
|
+
sourceId: `${format}:${sessionId}:${String(identity)}`, sourceHash: source.sourceHash,
|
|
77
|
+
occurredAt: intakeDate(assistant?.timestamp ?? request.timestamp), metadata: source.metadata,
|
|
78
|
+
warnings: [...source.warnings, ...(!assistant ? ["No assistant response was recorded for this request."] : [])], needsContext: true,
|
|
79
|
+
};
|
|
80
|
+
assertBoundedTaskJson(record);
|
|
81
|
+
normalizedBytes += new TextEncoder().encode(JSON.stringify(record)).length;
|
|
82
|
+
if (normalizedBytes > TASK_INTAKE_LIMITS.bytes)
|
|
83
|
+
throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");
|
|
84
|
+
return TaskIntakeRecordSchema.parse(record);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createRewardBinding } from "../rewards.js";
|
|
2
|
+
import { previewTaskIntake } from "./intake.js";
|
|
3
|
+
import { intakeId } from "./intake-contracts.js";
|
|
4
|
+
import { LearningDomainError } from "./errors.js";
|
|
5
|
+
import { LearningSourceSchema, TaskDefinitionSchema, TaskExampleSubmissionSchema, learningRef, sealLearningContent } from "./contracts.js";
|
|
6
|
+
import { learningEvidenceId } from "./repository.js";
|
|
7
|
+
import { createLearningTextAsset, verifyLearningTextAsset } from "./assets.js";
|
|
8
|
+
export async function importTaskIntake(transaction, input, now, submit) {
|
|
9
|
+
const preview = previewTaskIntake(input);
|
|
10
|
+
if (preview.contentHash !== input.expectedPreviewHash)
|
|
11
|
+
throw new LearningDomainError("task_intake_preview_changed", 409);
|
|
12
|
+
if (new Set(input.recordIds).size !== input.recordIds.length)
|
|
13
|
+
throw new LearningDomainError("task_intake_duplicate_selection", 422);
|
|
14
|
+
const selected = input.recordIds.map(id => {
|
|
15
|
+
const record = preview.records.find(record => record.id === id);
|
|
16
|
+
if (!record)
|
|
17
|
+
throw new LearningDomainError("task_intake_record_missing", 422, "Choose only valid records from the current preview.");
|
|
18
|
+
return record;
|
|
19
|
+
});
|
|
20
|
+
const id = `intake-${preview.contentHash}`;
|
|
21
|
+
// Keep the exact uploaded text once, privately, instead of duplicating a
|
|
22
|
+
// complete session/bundle in every normalized turn. Parts concatenate in
|
|
23
|
+
// path/index order and never split a UTF-16 surrogate pair.
|
|
24
|
+
const sourceAssets = [];
|
|
25
|
+
for (const file of input.files) {
|
|
26
|
+
let start = 0, part = 0;
|
|
27
|
+
do {
|
|
28
|
+
let end = Math.min(start + 131_072, file.text.length);
|
|
29
|
+
if (end < file.text.length && file.text.charCodeAt(end - 1) >= 0xd800 && file.text.charCodeAt(end - 1) <= 0xdbff)
|
|
30
|
+
end--;
|
|
31
|
+
const asset = createLearningTextAsset({ text: file.text.slice(start, end), path: `${id}/${file.path}.part-${String(part++).padStart(4, "0")}`,
|
|
32
|
+
mediaType: "text/plain", visibility: "host_private" });
|
|
33
|
+
const existing = await transaction.get("asset", asset.id, 1);
|
|
34
|
+
if (existing)
|
|
35
|
+
verifyLearningTextAsset(existing, asset.asset);
|
|
36
|
+
else
|
|
37
|
+
await transaction.put("asset", asset, 0);
|
|
38
|
+
sourceAssets.push(asset.asset);
|
|
39
|
+
start = end;
|
|
40
|
+
} while (start < file.text.length);
|
|
41
|
+
}
|
|
42
|
+
let source = await transaction.get("source", id);
|
|
43
|
+
if (!source) {
|
|
44
|
+
const binding = createRewardBinding({ schemaVersion: "openpond.rewardBinding.v1", id: `${id}-binding`, revision: 1,
|
|
45
|
+
sources: [], aggregation: "weighted_mean", unscorable: "exclude_optional_require_all_required" }, []);
|
|
46
|
+
const definition = TaskDefinitionSchema.parse(sealLearningContent({
|
|
47
|
+
schemaVersion: "openpond.taskDefinition.v1", id: `${id}-definition`, revision: 1, name: input.name,
|
|
48
|
+
description: `Imported ${input.format} records. Labels and task admission remain separate.`,
|
|
49
|
+
instructions: "Respond to the retained request using its supplied context.", category: "custom", familyNamespace: `intake-${input.format}`,
|
|
50
|
+
inputSchema: { type: "object" }, outputSchema: { type: "object" }, rewardBinding: learningRef(binding), harness: null,
|
|
51
|
+
contextRequirements: preview.records.some(record => record.needsContext) ? ["Review the imported history and configure its reusable input, tools and runtime before admitting tasks."] : [],
|
|
52
|
+
execution: { policy: { policyVisibleFields: ["input"], privilegedFields: ["expectedOutput", "evaluatorContext"], hiddenGraderRefs: [], connectedAppScopes: [] },
|
|
53
|
+
environment: { protocolVersion: "openpond.environment.v1", kind: "text", entrypoint: "openpond.text.v1", stateful: false,
|
|
54
|
+
deterministicSeeds: true, lifecycle: ["create", "reset", "step", "collect", "destroy"], networkPolicy: "none", defaultTimeoutMs: 30_000 }, tools: [], capabilities: [] },
|
|
55
|
+
}));
|
|
56
|
+
source = LearningSourceSchema.parse(sealLearningContent({ schemaVersion: "openpond.learningSource.v1", id, revision: 1, name: input.name,
|
|
57
|
+
kind: "direct", taskDefinition: learningRef(definition), enabled: true, allowedSplits: ["train", "validation", "test", "frozen_eval"],
|
|
58
|
+
mapping: null, adapterVersion: `openpond.intake.${input.format}.v1` }));
|
|
59
|
+
await transaction.put("binding", binding, 0);
|
|
60
|
+
await transaction.put("definition", definition, 0);
|
|
61
|
+
await transaction.put("source", source, 0);
|
|
62
|
+
}
|
|
63
|
+
const pointers = [{ kind: "source", id: source.id, revision: source.revision }];
|
|
64
|
+
for (const record of selected) {
|
|
65
|
+
const attemptId = intakeId("attempt", [record.id, record.sourceHash]);
|
|
66
|
+
const existing = await transaction.get("evidence", learningEvidenceId(source.id, record.id, attemptId), 1);
|
|
67
|
+
pointers.push(await submit(transaction, { action: "submit_example", operationId: input.operationId,
|
|
68
|
+
example: TaskExampleSubmissionSchema.parse({ schemaVersion: "openpond.taskExample.v1", sourceId: source.id,
|
|
69
|
+
idempotencyKey: intakeId("record", [preview.contentHash, record.id]), taskDefinition: source.taskDefinition,
|
|
70
|
+
exampleId: record.id, attemptId, occurredAt: record.occurredAt ?? existing?.submission.occurredAt ?? now,
|
|
71
|
+
familyKey: record.familyKey, split: record.split, input: record.input, observedOutput: record.observedOutput, expected: record.expected,
|
|
72
|
+
evaluatorContext: { intake: { format: preview.format, uploadHash: preview.contentHash, sourceHash: record.sourceHash,
|
|
73
|
+
needsContext: record.needsContext, warnings: record.warnings, timestampOrigin: record.occurredAt ? "source" : "import_time", metadata: record.metadata } },
|
|
74
|
+
assets: sourceAssets, provenance: { sourceRecordRef: record.sourceId, mappingHash: null },
|
|
75
|
+
}),
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
return pointers;
|
|
79
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { contentHash } from "@openpond/harness";
|
|
3
|
+
import { assertBoundedTaskJson } from "../task-schema.js";
|
|
4
|
+
import { TaskSplitSchema } from "../tasksets.js";
|
|
5
|
+
import { LearningJsonObjectSchema } from "./contracts.js";
|
|
6
|
+
import { parseTaskIntakeCsv } from "./intake-csv.js";
|
|
7
|
+
import { parseHermesSession, parseOpenClawBundle } from "./intake-history.js";
|
|
8
|
+
import { intakeDate, intakeId, TASK_INTAKE_LIMITS, TaskIntakeFileSchema, TaskIntakeFormatSchema, TaskIntakeRecordSchema, TaskIntakePreviewSchema } from "./intake-contracts.js";
|
|
9
|
+
const taskSchema = z.object({
|
|
10
|
+
instruction: z.string().trim().min(1).max(100_000), context: z.union([z.string(), LearningJsonObjectSchema]).optional(),
|
|
11
|
+
reference: z.union([z.string(), LearningJsonObjectSchema]).optional(), labels: z.union([z.string(), z.array(z.string()), LearningJsonObjectSchema]).optional(),
|
|
12
|
+
id: z.string().min(1).max(200).optional(), familyKey: z.string().min(1).max(200).optional(), split: TaskSplitSchema.optional(),
|
|
13
|
+
}).strict();
|
|
14
|
+
const structuredTaskSchema = z.object({
|
|
15
|
+
input: LearningJsonObjectSchema, observedOutput: LearningJsonObjectSchema.nullable().optional(), expectedOutput: LearningJsonObjectSchema.nullable().optional(),
|
|
16
|
+
id: z.string().min(1).max(200).optional(), familyKey: z.string().min(1).max(200).optional(), split: TaskSplitSchema.optional(),
|
|
17
|
+
occurredAt: z.string().datetime().optional(), labels: LearningJsonObjectSchema.optional(),
|
|
18
|
+
}).strict();
|
|
19
|
+
export function previewTaskIntake(input) {
|
|
20
|
+
const format = TaskIntakeFormatSchema.parse(input.format);
|
|
21
|
+
const files = z.array(TaskIntakeFileSchema).min(1).max(TASK_INTAKE_LIMITS.files).parse(input.files);
|
|
22
|
+
if (files.reduce((size, file) => size + new TextEncoder().encode(file.text).length, 0) > TASK_INTAKE_LIMITS.bytes)
|
|
23
|
+
throw new Error("Import exceeds the 5 MiB size limit.");
|
|
24
|
+
if (files.some(file => file.path.startsWith("/") || file.path.includes("\\") || file.path.split("/").some(part => !part || part === "." || part === "..")) || new Set(files.map(file => file.path)).size !== files.length)
|
|
25
|
+
throw new Error("Import contains an unsafe or duplicate file path.");
|
|
26
|
+
const records = [], issues = [];
|
|
27
|
+
const seen = new Map();
|
|
28
|
+
const splits = new Map();
|
|
29
|
+
let normalizedBytes = 0;
|
|
30
|
+
function attempt(file, row, parse) {
|
|
31
|
+
try {
|
|
32
|
+
const parsed = parse();
|
|
33
|
+
if (records.length + parsed.length > TASK_INTAKE_LIMITS.records)
|
|
34
|
+
throw new Error("Import exceeds the 1,000-record limit.");
|
|
35
|
+
const nextSeen = new Map(seen), nextSplits = new Map(splits);
|
|
36
|
+
let addedBytes = 0;
|
|
37
|
+
for (const record of parsed) {
|
|
38
|
+
assertBoundedTaskJson(record);
|
|
39
|
+
const hash = contentHash(record);
|
|
40
|
+
const existing = nextSeen.get(record.id);
|
|
41
|
+
if (existing && existing !== hash)
|
|
42
|
+
throw new Error("The same record identity has different content in this upload.");
|
|
43
|
+
if (!existing)
|
|
44
|
+
addedBytes += new TextEncoder().encode(JSON.stringify(record)).length;
|
|
45
|
+
nextSeen.set(record.id, hash);
|
|
46
|
+
for (const key of [`family:${record.familyKey}`, `input:${contentHash(record.input)}`]) {
|
|
47
|
+
if (nextSplits.has(key) && nextSplits.get(key) !== record.split)
|
|
48
|
+
throw new Error("The same task family or request occurs in different splits.");
|
|
49
|
+
nextSplits.set(key, record.split);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (normalizedBytes + addedBytes > TASK_INTAKE_LIMITS.bytes * 2)
|
|
53
|
+
throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");
|
|
54
|
+
for (const record of parsed) {
|
|
55
|
+
if (!seen.has(record.id))
|
|
56
|
+
records.push(record);
|
|
57
|
+
seen.set(record.id, contentHash(record));
|
|
58
|
+
}
|
|
59
|
+
for (const [key, split] of nextSplits)
|
|
60
|
+
splits.set(key, split);
|
|
61
|
+
normalizedBytes += addedBytes;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
issues.push({ file, row, message: error instanceof z.ZodError ? `Unsupported record fields or values (${error.issues.slice(0, 3).map(issue => issue.path.join(".") || "record").join(", ")}).` : error instanceof SyntaxError ? "Invalid JSON." : error instanceof Error ? error.message : "Invalid import record." });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (format === "openclaw")
|
|
68
|
+
attempt("manifest.json", null, () => parseOpenClawBundle(files));
|
|
69
|
+
else
|
|
70
|
+
for (const file of files) {
|
|
71
|
+
if (format === "jsonl" || format === "hermes") {
|
|
72
|
+
for (const [index, line] of file.text.split(/\r?\n/u).entries()) {
|
|
73
|
+
if (!line.trim())
|
|
74
|
+
continue;
|
|
75
|
+
if (issues.length >= TASK_INTAKE_LIMITS.records)
|
|
76
|
+
break;
|
|
77
|
+
attempt(file.path, index + 1, () => format === "hermes" ? parseHermesSession(JSON.parse(line)) : [normalizeTask(JSON.parse(line))]);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
let values;
|
|
82
|
+
try {
|
|
83
|
+
const value = format === "csv" ? parseTaskIntakeCsv(file.text) : JSON.parse(file.text);
|
|
84
|
+
values = Array.isArray(value) ? value : [value];
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
attempt(file.path, null, () => { throw error; });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (values.length > TASK_INTAKE_LIMITS.records) {
|
|
91
|
+
attempt(file.path, null, () => { throw new Error("Import exceeds the 1,000-record limit."); });
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
values.forEach((value, index) => attempt(file.path, index + (format === "csv" ? 2 : 1), () => [normalizeTask(value)]));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return TaskIntakePreviewSchema.parse({ schemaVersion: "openpond.taskIntakePreview.v1", format, contentHash: contentHash({ format, files }), records, issues: issues.slice(0, 1_000) });
|
|
98
|
+
}
|
|
99
|
+
function normalizeTask(value) {
|
|
100
|
+
const parsed = z.union([taskSchema, structuredTaskSchema]).parse(value);
|
|
101
|
+
const simple = "instruction" in parsed;
|
|
102
|
+
const input = simple ? { instruction: parsed.instruction, ...(parsed.context === undefined ? {} : { context: parsed.context }) } : parsed.input;
|
|
103
|
+
const expected = simple ? parsed.reference === undefined ? null : typeof parsed.reference === "string" ? { text: parsed.reference } : parsed.reference : parsed.expectedOutput ?? null;
|
|
104
|
+
const observedOutput = simple ? null : parsed.observedOutput ?? null;
|
|
105
|
+
// Without an explicit family, identical requests stay together even when
|
|
106
|
+
// their imported labels or reference answers differ.
|
|
107
|
+
const familyKey = parsed.familyKey ?? intakeId("family", input);
|
|
108
|
+
const id = parsed.id ?? intakeId("task", { input, expected, observedOutput });
|
|
109
|
+
return TaskIntakeRecordSchema.parse({ id, familyKey, split: parsed.split ?? "train", kind: observedOutput ? "attempt" : "task", input,
|
|
110
|
+
expected, observedOutput, sourceId: id, sourceHash: contentHash(value), occurredAt: simple ? null : intakeDate(parsed.occurredAt),
|
|
111
|
+
metadata: parsed.labels === undefined ? {} : { importedLabels: parsed.labels, labelOrigin: "unverified_import" }, warnings: [], needsContext: false });
|
|
112
|
+
}
|
|
@@ -5,7 +5,12 @@ import { LearningJsonObjectSchema, LearningRevisionRefSchema, LearningSourceCont
|
|
|
5
5
|
import { RewardBindingContentSchema, RewardReleaseContentSchema } from "../rewards.js";
|
|
6
6
|
import { AuthoringDraftInputSchema, AuthoringDraftFinalizationSchema } from "./authoring.js";
|
|
7
7
|
import { LearningTextAssetContentSchema } from "./assets.js";
|
|
8
|
+
import { TaskIntakeFileSchema, TaskIntakeFormatSchema } from "./intake-contracts.js";
|
|
8
9
|
const command = z.object({ operationId: ReleaseIdSchema });
|
|
10
|
+
export const ImportTaskIntakeCommandSchema = command.extend({ action: z.literal("import_intake"), format: TaskIntakeFormatSchema,
|
|
11
|
+
files: z.array(TaskIntakeFileSchema).min(1).max(100), expectedPreviewHash: z.string().length(64),
|
|
12
|
+
name: z.string().trim().min(1).max(500), recordIds: z.array(z.string().min(1).max(200)).min(1).max(90),
|
|
13
|
+
}).strict();
|
|
9
14
|
const publish = command.extend({ action: z.literal("publish"), expectedRevision: z.number().int().nonnegative(), finalizeDraft: AuthoringDraftFinalizationSchema.optional() });
|
|
10
15
|
export const PublishLearningResourceCommandSchema = z.discriminatedUnion("kind", [
|
|
11
16
|
publish.extend({ kind: z.literal("asset"), content: LearningTextAssetContentSchema }).strict(),
|
|
@@ -41,4 +46,4 @@ export const ReserveLearningIterationCommandSchema = command.extend({ action: z.
|
|
|
41
46
|
export const CancelLearningIterationReservationCommandSchema = command.extend({ action: z.literal("cancel_iteration_reservation"), iterationId: ReleaseIdSchema, expectedRevision: z.number().int().positive() }).strict();
|
|
42
47
|
export const CancelLearningIterationCommandSchema = command.extend({ action: z.literal("cancel_iteration"), iterationId: ReleaseIdSchema, expectedRevision: z.number().int().positive() }).strict();
|
|
43
48
|
export const RetryLearningIterationDispatchCommandSchema = command.extend({ action: z.literal("retry_iteration_dispatch"), iterationId: ReleaseIdSchema, expectedRevision: z.number().int().positive() }).strict();
|
|
44
|
-
export const LearningCommandSchema = z.union([CancelLearningIterationCommandSchema, RetryLearningIterationDispatchCommandSchema, CancelLearningIterationReservationCommandSchema, ReserveLearningIterationCommandSchema, QueueRewardCheckCommandSchema, CancelRewardCheckCommandSchema, SaveAuthoringDraftCommandSchema, ArchiveAuthoringDraftCommandSchema, PublishLearningResourceCommandSchema, PublishLearningResourcesCommandSchema, SubmitTaskExampleCommandSchema, SubmitTaskFeedbackCommandSchema, ApplyTaskCorrectionCommandSchema, ResolveTaskFeedbackCommandSchema, QueueTaskGradeCommandSchema, ReviewTaskEvidenceCommandSchema, SealTaskBatchCommandSchema, CancelTaskGradeCommandSchema]);
|
|
49
|
+
export const LearningCommandSchema = z.union([ImportTaskIntakeCommandSchema, CancelLearningIterationCommandSchema, RetryLearningIterationDispatchCommandSchema, CancelLearningIterationReservationCommandSchema, ReserveLearningIterationCommandSchema, QueueRewardCheckCommandSchema, CancelRewardCheckCommandSchema, SaveAuthoringDraftCommandSchema, ArchiveAuthoringDraftCommandSchema, PublishLearningResourceCommandSchema, PublishLearningResourcesCommandSchema, SubmitTaskExampleCommandSchema, SubmitTaskFeedbackCommandSchema, ApplyTaskCorrectionCommandSchema, ResolveTaskFeedbackCommandSchema, QueueTaskGradeCommandSchema, ReviewTaskEvidenceCommandSchema, SealTaskBatchCommandSchema, CancelTaskGradeCommandSchema]);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { learningRef, sameLearningRef, TaskRatingSchema } from "./contracts.js";
|
|
2
|
+
import { LearningDomainError } from "./errors.js";
|
|
3
|
+
/** Copy a retained label into editable check data while preserving its exact origin. */
|
|
4
|
+
export function rewardFixtureFromRating(evidence, feedback, scale = { minimum: 0, maximum: 1 }) {
|
|
5
|
+
if (!feedback.evidence || !sameLearningRef(feedback.evidence, learningRef(evidence)) || feedback.submission.expectedEvidenceHash !== evidence.contentHash || feedback.submission.kind !== "outcome" || !evidence.submission.observedOutput)
|
|
6
|
+
throw new LearningDomainError("rating_fixture_evidence_mismatch", 422);
|
|
7
|
+
const rating = TaskRatingSchema.parse(feedback.submission.value);
|
|
8
|
+
if (!Number.isFinite(scale.minimum) || !Number.isFinite(scale.maximum) || scale.minimum >= scale.maximum)
|
|
9
|
+
throw new LearningDomainError("rating_fixture_scale_invalid", 422);
|
|
10
|
+
const score = scale.minimum + (rating.score - rating.scale.minimum) / (rating.scale.maximum - rating.scale.minimum) * (scale.maximum - scale.minimum);
|
|
11
|
+
return {
|
|
12
|
+
id: `label-${feedback.id}-${feedback.revision}`, name: evidence.submission.exampleId,
|
|
13
|
+
input: JSON.stringify(evidence.submission.input, null, 2), output: JSON.stringify(evidence.submission.observedOutput, null, 2),
|
|
14
|
+
expectedOutput: evidence.submission.expected ? JSON.stringify(evidence.submission.expected, null, 2) : "",
|
|
15
|
+
evaluatorContext: evidence.submission.evaluatorContext ? JSON.stringify(evidence.submission.evaluatorContext, null, 2) : "",
|
|
16
|
+
artifactRefs: [], runtimeEventRefs: [], infrastructureError: "", expectedStatus: "scored", minimumScore: String(score), maximumScore: String(score), expectedPassed: "any",
|
|
17
|
+
sourceLabel: { evidence: learningRef(evidence), feedback: { id: feedback.id, revision: feedback.revision } },
|
|
18
|
+
};
|
|
19
|
+
}
|
package/dist/learning/service.js
CHANGED
|
@@ -17,6 +17,7 @@ import { LearningConflictError, learningEvidenceId, learningOperationId, require
|
|
|
17
17
|
import { validateSourceSubmission } from "./admission.js";
|
|
18
18
|
import { LearningTextAssetSchema, verifyLearningTextAsset } from "./assets.js";
|
|
19
19
|
import { LearningRevisionRefSchema } from "./contracts.js";
|
|
20
|
+
import { importTaskIntake } from "./intake-service.js";
|
|
20
21
|
export function createLearningService(repository, options = {}) {
|
|
21
22
|
const now = options.now ?? (() => new Date().toISOString());
|
|
22
23
|
async function command(context, raw) {
|
|
@@ -35,6 +36,9 @@ export function createLearningService(repository, options = {}) {
|
|
|
35
36
|
}
|
|
36
37
|
let pointers;
|
|
37
38
|
switch (input.action) {
|
|
39
|
+
case "import_intake":
|
|
40
|
+
pointers = await importTaskIntake(transaction, input, now(), submit);
|
|
41
|
+
break;
|
|
38
42
|
case "cancel_iteration":
|
|
39
43
|
case "retry_iteration_dispatch":
|
|
40
44
|
pointers = await commandLearningIterationDispatch(transaction, input, now());
|
|
@@ -70,7 +74,7 @@ export function createLearningService(repository, options = {}) {
|
|
|
70
74
|
pointers = [await submit(transaction, input)];
|
|
71
75
|
break;
|
|
72
76
|
case "submit_feedback":
|
|
73
|
-
pointers = [await feedback(transaction, input)];
|
|
77
|
+
pointers = [await feedback(transaction, input, context.actor)];
|
|
74
78
|
break;
|
|
75
79
|
case "apply_correction":
|
|
76
80
|
pointers = await correct(transaction, input, context.actor.id);
|
|
@@ -193,16 +197,19 @@ export function createLearningService(repository, options = {}) {
|
|
|
193
197
|
} while (afterId);
|
|
194
198
|
return pointer("evidence", evidence);
|
|
195
199
|
}
|
|
196
|
-
async function feedback(transaction, input) {
|
|
200
|
+
async function feedback(transaction, input, actor) {
|
|
197
201
|
const source = await requireLearningResource(transaction, "source", input.feedback.sourceId);
|
|
198
202
|
if (!source.enabled)
|
|
199
203
|
throw new LearningDomainError("learning_source_disabled", 409);
|
|
200
204
|
const evidenceId = learningEvidenceId(source.id, input.feedback.exampleId, input.feedback.attemptId);
|
|
201
205
|
const evidence = await transaction.get("evidence", evidenceId);
|
|
206
|
+
if (input.feedback.value.schemaVersion === "openpond.taskRating.v1" && (!evidence || evidence.contentHash !== input.feedback.expectedEvidenceHash || !evidence.submission.observedOutput))
|
|
207
|
+
throw new LearningDomainError("task_rating_evidence_stale", 409, "Open the current observed response before submitting a rating.");
|
|
202
208
|
const record = TaskFeedbackSchema.parse({
|
|
203
209
|
schemaVersion: "openpond.taskFeedbackRecord.v1", id: `feedback-${contentHash([source.id, input.feedback.idempotencyKey])}`,
|
|
204
210
|
submission: input.feedback, status: evidence ? "pending_review" : "pending_example",
|
|
205
211
|
evidence: evidence ? learningRef(evidence) : null, createdAt: now(), revision: 1,
|
|
212
|
+
submittedBy: { id: actor.id, role: actor.role, sourceId: actor.sourceId ?? null },
|
|
206
213
|
});
|
|
207
214
|
await transaction.put("feedback", record, 0, { parentId: evidenceId, status: record.status });
|
|
208
215
|
return pointer("feedback", record);
|
|
@@ -348,6 +355,8 @@ export function createLearningService(repository, options = {}) {
|
|
|
348
355
|
},
|
|
349
356
|
async list(context, kind, query = {}) {
|
|
350
357
|
authorizeRead(context);
|
|
358
|
+
if (query.reviewState !== undefined && (kind !== "evidence" || !["inbox", "reviewed"].includes(query.reviewState)))
|
|
359
|
+
throw new LearningDomainError("learning_review_filter_invalid", 400);
|
|
351
360
|
const limit = Math.max(1, Math.min(100, Math.trunc(query.limit ?? 50)));
|
|
352
361
|
return repository.transaction(context.scope, (transaction) => transaction.list(kind, { ...query, limit }));
|
|
353
362
|
},
|