@openpond/evals 0.10.8 → 0.10.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LEARNING.md +41 -0
  2. package/dist/graders.js +19 -4
  3. package/dist/learning/admission.js +4 -0
  4. package/dist/learning/budgeted-reward-fixtures.js +34 -0
  5. package/dist/learning/contracts.js +4 -0
  6. package/dist/learning/grade-judge-budget.js +26 -0
  7. package/dist/learning/index.js +8 -0
  8. package/dist/learning/intake-contracts.js +30 -0
  9. package/dist/learning/intake-csv.js +59 -0
  10. package/dist/learning/intake-history.js +87 -0
  11. package/dist/learning/intake-service.js +79 -0
  12. package/dist/learning/intake-text.js +14 -0
  13. package/dist/learning/intake.js +115 -0
  14. package/dist/learning/judge-budget.js +59 -0
  15. package/dist/learning/model-judge.js +49 -0
  16. package/dist/learning/operations.js +8 -1
  17. package/dist/learning/reward-authoring.js +4 -0
  18. package/dist/learning/reward-calibration.js +66 -0
  19. package/dist/learning/reward-check-budget.js +27 -0
  20. package/dist/learning/reward-check-service.js +2 -2
  21. package/dist/learning/reward-check-worker.js +10 -2
  22. package/dist/learning/reward-checks.js +4 -1
  23. package/dist/learning/reward-fixture-executor.js +3 -2
  24. package/dist/learning/service.js +34 -5
  25. package/dist/rewards.js +21 -7
  26. package/dist/rollouts.js +2 -2
  27. package/dist/types/graders.d.ts +51 -0
  28. package/dist/types/graders.d.ts.map +1 -1
  29. package/dist/types/learning/admission.d.ts +6 -0
  30. package/dist/types/learning/admission.d.ts.map +1 -1
  31. package/dist/types/learning/batch-service.d.ts +1 -0
  32. package/dist/types/learning/batch-service.d.ts.map +1 -1
  33. package/dist/types/learning/budgeted-reward-fixtures.d.ts +27 -0
  34. package/dist/types/learning/budgeted-reward-fixtures.d.ts.map +1 -0
  35. package/dist/types/learning/contracts.d.ts +304 -0
  36. package/dist/types/learning/contracts.d.ts.map +1 -1
  37. package/dist/types/learning/grade-judge-budget.d.ts +10 -0
  38. package/dist/types/learning/grade-judge-budget.d.ts.map +1 -0
  39. package/dist/types/learning/index.d.ts +8 -0
  40. package/dist/types/learning/index.d.ts.map +1 -1
  41. package/dist/types/learning/intake-contracts.d.ts +87 -0
  42. package/dist/types/learning/intake-contracts.d.ts.map +1 -0
  43. package/dist/types/learning/intake-csv.d.ts +3 -0
  44. package/dist/types/learning/intake-csv.d.ts.map +1 -0
  45. package/dist/types/learning/intake-history.d.ts +5 -0
  46. package/dist/types/learning/intake-history.d.ts.map +1 -0
  47. package/dist/types/learning/intake-service.d.ts +8 -0
  48. package/dist/types/learning/intake-service.d.ts.map +1 -0
  49. package/dist/types/learning/intake-text.d.ts +6 -0
  50. package/dist/types/learning/intake-text.d.ts.map +1 -0
  51. package/dist/types/learning/intake.d.ts +7 -0
  52. package/dist/types/learning/intake.d.ts.map +1 -0
  53. package/dist/types/learning/iteration-dispatch-contracts.d.ts +1 -1
  54. package/dist/types/learning/iteration-reservation-contracts.d.ts +1 -1
  55. package/dist/types/learning/judge-budget.d.ts +43 -0
  56. package/dist/types/learning/judge-budget.d.ts.map +1 -0
  57. package/dist/types/learning/model-judge.d.ts +29 -0
  58. package/dist/types/learning/model-judge.d.ts.map +1 -0
  59. package/dist/types/learning/operations.d.ts +80 -0
  60. package/dist/types/learning/operations.d.ts.map +1 -1
  61. package/dist/types/learning/repository.d.ts +178 -4
  62. package/dist/types/learning/repository.d.ts.map +1 -1
  63. package/dist/types/learning/reward-authoring.d.ts.map +1 -1
  64. package/dist/types/learning/reward-calibration.d.ts +129 -0
  65. package/dist/types/learning/reward-calibration.d.ts.map +1 -0
  66. package/dist/types/learning/reward-check-budget.d.ts +12 -0
  67. package/dist/types/learning/reward-check-budget.d.ts.map +1 -0
  68. package/dist/types/learning/reward-check-service.d.ts +1 -1
  69. package/dist/types/learning/reward-check-service.d.ts.map +1 -1
  70. package/dist/types/learning/reward-check-worker.d.ts.map +1 -1
  71. package/dist/types/learning/reward-checks.d.ts +84 -0
  72. package/dist/types/learning/reward-checks.d.ts.map +1 -1
  73. package/dist/types/learning/reward-fixture-executor.d.ts +3 -0
  74. package/dist/types/learning/reward-fixture-executor.d.ts.map +1 -1
  75. package/dist/types/learning/schedule-contracts.d.ts +1 -1
  76. package/dist/types/learning/service.d.ts.map +1 -1
  77. package/dist/types/learning/transport.d.ts +218 -5
  78. package/dist/types/learning/transport.d.ts.map +1 -1
  79. package/dist/types/rewards.d.ts +107 -0
  80. package/dist/types/rewards.d.ts.map +1 -1
  81. package/dist/types/rollouts.d.ts.map +1 -1
  82. package/package.json +1 -1
  83. package/schemas/learning/v1/binding.schema.json +0 -1
  84. package/schemas/learning/v1/command-request.schema.json +407 -256
  85. package/schemas/learning/v1/decision.schema.json +192 -1
  86. package/schemas/learning/v1/definition.schema.json +19 -7
  87. package/schemas/learning/v1/grade.schema.json +335 -4
  88. package/schemas/learning/v1/reward.schema.json +22 -0
  89. package/schemas/learning/v1/reward_check.schema.json +335 -3
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
@@ -117,6 +143,12 @@ runtime/package identity and settles only after cleanup. The isolated adapter ru
117
143
  portable deterministic checks and authored JavaScript with the supplied interpreter.
118
144
  Human review remains pending; missing judge/learned-model adapters remain unavailable.
119
145
  No fixture result implicitly calibrates a judge or qualifies a training runtime.
146
+ `publish_checked_reward` explicitly publishes the exact saved judge draft after a
147
+ completed check covers both passing and failing examples. The service revalidates
148
+ fixture hashes and persisted provider receipts, records `calibrationCheckRef`, and
149
+ closes the draft in the same transaction. Generic publication cannot manufacture
150
+ a passed calibration or reuse that check after changing the model, temperature,
151
+ rubric or fixtures. Metadata-only edits may retain the same calibration evidence.
120
152
  Per-fixture results distinguish a scored rejection, unavailable grading and grader
121
153
  failure, and record whether each outcome matched its authored expectation.
122
154
 
@@ -125,6 +157,15 @@ readable after publication. Editing source or fixtures must mark prior checks as
125
157
  historical. `cancel_reward_check` requests cancellation with revision concurrency;
126
158
  the worker publishes terminal cancellation only after execution-owner cleanup.
127
159
 
160
+ `createBudgetedRewardFixtureExecutor` and `createTaskGradeJudgeBudgetStore` retain
161
+ judge calls in the owning run. Reserve the full charge ceiling before dispatch;
162
+ late settlement survives cancellation and expired ownership. Missing/partial
163
+ usage leaves the full reservation committed, and an uncertain request cannot be
164
+ retried under the same call identity. Hosts inject a `BoundJudgeProvider` that
165
+ prepares without inference and dispatches once. The local OpenPond transport uses
166
+ catalog pricing/context limits, exact model IDs and bounded output; it rejects
167
+ revision pins because OpChat does not currently expose revision enforcement.
168
+
128
169
  ### Source and execution ownership
129
170
 
130
171
  Authored verifier code and rubrics use immutable `asset` resources. Publish source
package/dist/graders.js CHANGED
@@ -2,6 +2,18 @@ import { z } from "zod";
2
2
  import { FailureClassSchema, ReleaseHashSchema, ReleaseIdSchema, contentHash } from "@openpond/harness";
3
3
  import { evaluateDeterministicGrader } from "./deterministic-graders.js";
4
4
  export { evaluateDeterministicGrader, portableDeterministicCheck } from "./deterministic-graders.js";
5
+ export const ModelJudgeReceiptSchema = z.object({
6
+ schemaVersion: z.literal("openpond.modelJudgeReceipt.v1"),
7
+ providerId: z.string().trim().min(1).max(200),
8
+ modelId: z.string().trim().min(1).max(500),
9
+ modelRevision: z.string().trim().min(1).max(500).nullable(),
10
+ responseId: z.string().trim().min(1).max(500).nullable(),
11
+ requestHash: ReleaseHashSchema,
12
+ responseHash: ReleaseHashSchema,
13
+ inputTokens: z.number().int().nonnegative().nullable(),
14
+ outputTokens: z.number().int().nonnegative().nullable(),
15
+ costUsd: z.number().finite().nonnegative().nullable(),
16
+ }).strict();
5
17
  export const GraderEvidenceContentSchema = z.object({
6
18
  schemaVersion: z.literal("openpond.graderEvidence.v1"),
7
19
  graderId: ReleaseIdSchema,
@@ -13,6 +25,7 @@ export const GraderEvidenceContentSchema = z.object({
13
25
  feedback: z.array(z.string().max(20_000)).max(1_000),
14
26
  visibleEvidenceRefs: z.array(ReleaseIdSchema).max(10_000),
15
27
  privilegedEvidenceRefs: z.array(ReleaseIdSchema).max(10_000),
28
+ modelJudgeReceipt: ModelJudgeReceiptSchema.optional(),
16
29
  }).strict();
17
30
  export const GraderEvidenceSchema = GraderEvidenceContentSchema.extend({ contentHash: ReleaseHashSchema }).strict();
18
31
  export async function gradeEvidence(input) {
@@ -29,9 +42,11 @@ export async function gradeEvidence(input) {
29
42
  }
30
43
  return Promise.all(input.graders.map(async (grader) => {
31
44
  if (grader.kind === "model_judge") {
32
- if (!input.modelJudge || grader.calibrationStatus !== "passed")
45
+ if (!input.modelJudge || (grader.calibrationStatus !== "passed" && input.purpose !== "fixture_calibration"))
33
46
  return evidence(grader, unavailable("Model judge is unavailable or uncalibrated."));
34
- return evidence(grader, await input.modelJudge({ grader, task: input.task, evidence: input.evidence }));
47
+ input.signal?.throwIfAborted();
48
+ const result = await input.modelJudge({ grader, task: input.task, evidence: input.evidence, signal: input.signal });
49
+ return evidence(grader, { ...result, rewardEligible: input.purpose === "fixture_calibration" ? false : result.rewardEligible });
35
50
  }
36
51
  if (grader.kind === "custom_verifier") {
37
52
  if (!input.customVerifier)
@@ -111,11 +126,11 @@ export function aggregateGraderScores(input) {
111
126
  failureClass: infrastructure ? "infrastructure_failure" : score === null ? "grader_failure" : passed ? null : "policy_failure",
112
127
  gradingStatus: !input.graders.length && !infrastructure ? "not_configured" : score === null ? "unscorable" : "scored" });
113
128
  }
114
- export const TaskGradeSchema = GradeSummarySchema.extend({
129
+ export const TaskGradeSchema = /* @__PURE__ */ (() => GradeSummarySchema.extend({
115
130
  schemaVersion: z.literal("openpond.taskGrade.v1"),
116
131
  taskHash: ReleaseHashSchema, evidenceHash: ReleaseHashSchema, graderSetHash: ReleaseHashSchema,
117
132
  components: z.array(GraderEvidenceSchema).max(1_000), contentHash: ReleaseHashSchema,
118
- }).strict();
133
+ }).strict())();
119
134
  export async function gradeTaskEvidence(input) {
120
135
  const components = await gradeEvidence(input);
121
136
  const content = { schemaVersion: "openpond.taskGrade.v1",
@@ -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);
@@ -0,0 +1,34 @@
1
+ import { contentHash } from "@openpond/harness";
2
+ import { verifyLearningTextAsset } from "./assets.js";
3
+ import { createBudgetedJudgeExecutor } from "./judge-budget.js";
4
+ import { createBoundModelJudgeRunner } from "./model-judge.js";
5
+ import { createRewardCheckJudgeBudgetStore } from "./reward-check-budget.js";
6
+ import { createIsolatedRewardFixtureExecutor } from "./reward-fixture-executor.js";
7
+ import { requireLearningResource } from "./repository.js";
8
+ export function createBudgetedRewardFixtureExecutor(options) {
9
+ return createIsolatedRewardFixtureExecutor({
10
+ runtime: options.runtime, executeJavaScript: options.executeJavaScript,
11
+ async cancelModelJudge(input) {
12
+ const run = await options.repository.transaction(input.scope, tx => requireLearningResource(tx, "reward_check", input.run.id));
13
+ if (run.judgeCalls?.some(call => call.status === "reserved"))
14
+ return false;
15
+ return options.provider.cancel({ ...input, run });
16
+ },
17
+ async createModelJudge(input) {
18
+ const budget = createRewardCheckJudgeBudgetStore({ repository: options.repository, scope: input.scope, run: input.run });
19
+ return createBoundModelJudgeRunner({
20
+ async readRubric(reference) {
21
+ const asset = input.assets.find(asset => asset.id === reference.id);
22
+ if (!asset)
23
+ throw new Error("reward_check_rubric_missing");
24
+ return verifyLearningTextAsset(asset, reference);
25
+ },
26
+ async executeBudgeted(request, signal) {
27
+ const prepared = await options.provider.prepare(request, { scope: input.scope, run: input.run });
28
+ const execute = createBudgetedJudgeExecutor({ store: budget, maximumCharge: () => prepared.maximumChargeUsd, dispatch: (_request, signal) => prepared.dispatch(signal) });
29
+ return execute(`fixture-${contentHash([input.fixture, input.reward.contentHash])}`, request, signal);
30
+ },
31
+ });
32
+ },
33
+ });
34
+ }
@@ -4,6 +4,7 @@ import { ImmutableAssetRefSchema, ImmutableReleaseRefSchema, ReleaseHashSchema,
4
4
  import { RewardBindingSchema, RewardCompositionSchema, RewardReleaseRefSchema, RewardReleaseSchema } from "../rewards.js";
5
5
  import { TaskRecordSchema, TaskSplitSchema, TasksetReleaseContentSchema } from "../tasksets.js";
6
6
  import { assertBoundedTaskJson, validateTaskSchema } from "../task-schema.js";
7
+ import { JudgeCallReservationSchema } from "./judge-budget.js";
7
8
  export const LearningJsonObjectSchema = z.record(z.string(), z.json());
8
9
  export const LearningRevisionRefSchema = RewardReleaseRefSchema;
9
10
  export const LearningJsonPointerSchema = z.string().max(2_000).refine((value) => value === "" || (value.startsWith("/") && !/~(?![01])/u.test(value)), "Use an RFC 6901 JSON pointer.");
@@ -19,6 +20,7 @@ export const TaskDefinitionContentSchema = z.object({
19
20
  inputSchema: z.record(z.string(), z.unknown()),
20
21
  outputSchema: z.record(z.string(), z.unknown()),
21
22
  requiredOutputs: TaskRecordSchema.shape.requiredOutputs,
23
+ contextRequirements: z.array(z.string().trim().min(1).max(2_000)).max(100).optional(),
22
24
  rewardBinding: LearningRevisionRefSchema,
23
25
  harness: ImmutableReleaseRefSchema.nullable(),
24
26
  execution: TasksetReleaseContentSchema.pick({ policy: true, environment: true, environmentRelease: true, tools: true, capabilities: true, verifierSetRelease: true }).strict(),
@@ -291,6 +293,8 @@ export const TaskGradeRunSchema = z.object({
291
293
  attemptCount: z.number().int().nonnegative(),
292
294
  timeoutMs: z.number().int().min(100).max(300_000),
293
295
  maximumSpendUsd: z.number().nonnegative().max(1_000),
296
+ judgeCalls: z.array(JudgeCallReservationSchema).max(10_000).optional(),
297
+ requestedBy: ReleaseIdSchema.optional(),
294
298
  failure: z.string().max(20_000).nullable(),
295
299
  createdAt: ReleaseTimestampSchema,
296
300
  updatedAt: ReleaseTimestampSchema,
@@ -0,0 +1,26 @@
1
+ import { contentHash } from "@openpond/harness";
2
+ import { requireLearningResource } from "./repository.js";
3
+ import { TaskGradeRunSchema } from "./contracts.js";
4
+ export function createTaskGradeJudgeBudgetStore(input) {
5
+ const now = input.now ?? (() => new Date().toISOString());
6
+ const identity = (run) => contentHash([run.evidence, run.binding, run.target, run.output]);
7
+ return {
8
+ transaction(intent, update) {
9
+ return input.repository.transaction(input.scope, async (tx) => {
10
+ const current = await requireLearningResource(tx, "grade", input.run.id);
11
+ if (identity(current) !== identity(input.run))
12
+ throw new Error("model_judge_budget_snapshot_changed");
13
+ if (intent === "dispatch" && (current.status !== "running" || !current.leaseOwner || current.leaseOwner !== input.run.leaseOwner
14
+ || current.attemptCount !== input.run.attemptCount || !current.leaseExpiresAt || Date.parse(current.leaseExpiresAt) <= Date.parse(now())))
15
+ throw new Error("model_judge_budget_owner_inactive");
16
+ const calls = current.judgeCalls ?? [];
17
+ const next = update({ maximumSpendUsd: current.maximumSpendUsd, calls });
18
+ if (contentHash(next.calls) !== contentHash(calls)) {
19
+ const updated = TaskGradeRunSchema.parse({ ...current, revision: current.revision + 1, judgeCalls: next.calls, updatedAt: now() });
20
+ await tx.put("grade", updated, current.revision, { parentId: current.evidence.id, status: current.status });
21
+ }
22
+ return next.result;
23
+ });
24
+ },
25
+ };
26
+ }
@@ -10,7 +10,15 @@ export * from "./errors.js";
10
10
  export * from "./authoring.js";
11
11
  export * from "./reward-authoring.js";
12
12
  export * from "./rating-reward-fixture.js";
13
+ export * from "./intake-contracts.js";
14
+ export * from "./intake.js";
15
+ export * from "./model-judge.js";
16
+ export * from "./judge-budget.js";
17
+ export * from "./reward-check-budget.js";
18
+ export * from "./grade-judge-budget.js";
19
+ export * from "./budgeted-reward-fixtures.js";
13
20
  export * from "./reward-checks.js";
21
+ export * from "./reward-calibration.js";
14
22
  export * from "./reward-check-worker.js";
15
23
  export * from "./reward-fixture-executor.js";
16
24
  export * from "./iteration-reservation-contracts.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,87 @@
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
+ import { structuredIntakeText } from "./intake-text.js";
7
+ const messageSchema = z.object({ role: z.string().min(1), content: z.json().nullable().optional() }).catchall(z.json());
8
+ const hermesSchema = z.object({ id: z.string().min(1), messages: z.array(messageSchema).min(1).max(TASK_INTAKE_LIMITS.messages),
9
+ lineage_session_ids: z.array(z.string()).optional(), parent_session_id: z.string().nullable().optional() }).catchall(z.json());
10
+ export function parseHermesSession(value) {
11
+ const session = hermesSchema.parse(value);
12
+ const family = session.lineage_session_ids?.[0] ?? session.parent_session_id ?? session.id;
13
+ const { messages: _messages, segments: _segments, ...metadata } = session;
14
+ return historyRecords("hermes", session.id, family, session.messages, {
15
+ sourceHash: contentHash(value), metadata: { session: metadata },
16
+ warnings: ["Imported session context and tools need review before this can become an executable task."],
17
+ });
18
+ }
19
+ const manifestSchema = z.object({ traceSchema: z.literal("openclaw-trajectory"), schemaVersion: z.literal(1),
20
+ traceId: z.string().min(1), sessionId: z.string().min(1), leafId: z.string().nullable(),
21
+ eventCount: z.number().int().nonnegative(), warnings: z.array(LearningJsonObjectSchema).optional() }).catchall(z.json());
22
+ const eventSchema = z.object({ traceSchema: z.literal("openclaw-trajectory"), schemaVersion: z.literal(1),
23
+ traceId: z.string(), sessionId: z.string(), seq: z.number().int().nonnegative(), type: z.string(), ts: z.string() }).catchall(z.json());
24
+ const branchSchema = z.object({ header: LearningJsonObjectSchema.nullable(), leafId: z.string().nullable(),
25
+ entries: z.array(z.object({ id: z.string().min(1), type: z.string().min(1), parentId: z.string().nullable().optional(),
26
+ message: messageSchema.optional() }).catchall(z.json())).max(TASK_INTAKE_LIMITS.messages) }).strict();
27
+ /** Takes named bundle files; never extracts paths or runs uploaded code. */
28
+ export function parseOpenClawBundle(files) {
29
+ const read = (path) => {
30
+ const file = files.find(file => file.path === path);
31
+ if (!file)
32
+ throw new Error(`OpenClaw bundle is missing ${path}.`);
33
+ return structuredIntakeText(file.text);
34
+ };
35
+ const manifest = manifestSchema.parse(JSON.parse(read("manifest.json")));
36
+ const branch = branchSchema.parse(JSON.parse(read("session-branch.json")));
37
+ if (branch.leafId !== manifest.leafId)
38
+ throw new Error("OpenClaw manifest and session branch identify different leaves.");
39
+ const events = read("events.jsonl").split(/\r?\n/u).filter(line => line.trim()).map(line => eventSchema.parse(JSON.parse(line)));
40
+ if (events.length !== manifest.eventCount || events.some(event => event.traceId !== manifest.traceId || event.sessionId !== manifest.sessionId))
41
+ throw new Error("OpenClaw events do not match the manifest identity or count.");
42
+ if (branch.header && branch.header.id !== manifest.sessionId)
43
+ throw new Error("OpenClaw session header does not match the manifest.");
44
+ const ids = new Set();
45
+ for (const [index, entry] of branch.entries.entries()) {
46
+ if (ids.has(entry.id))
47
+ throw new Error("OpenClaw branch contains duplicate entry IDs.");
48
+ if (index && entry.parentId !== branch.entries[index - 1].id)
49
+ throw new Error("OpenClaw branch is incomplete or out of order.");
50
+ ids.add(entry.id);
51
+ }
52
+ if (branch.entries.length && branch.entries.at(-1).id !== branch.leafId)
53
+ throw new Error("OpenClaw branch does not reach its declared leaf.");
54
+ const messages = branch.entries.filter(entry => entry.type === "message" && entry.message).map(entry => ({ ...entry.message, entryId: entry.id,
55
+ timestamp: typeof entry.timestamp === "string" ? entry.timestamp : typeof entry.message.timestamp === "number" ? new Date(entry.message.timestamp).toISOString() : null }));
56
+ return historyRecords("openclaw", manifest.sessionId, manifest.sessionId, messages, {
57
+ sourceHash: contentHash(files), metadata: { manifest, sourceFiles: files.map(file => file.path) },
58
+ warnings: ["Imported trajectory context and tools need review before this can become an executable task.",
59
+ ...(manifest.warnings ?? []).map(warning => typeof warning.message === "string" ? warning.message.slice(0, 2_000) : "The source exporter reported incomplete context.")],
60
+ });
61
+ }
62
+ function historyRecords(format, sessionId, family, messages, source) {
63
+ const starts = messages.flatMap((message, index) => message.role === "user" ? [index] : []);
64
+ if (!starts.length)
65
+ throw new Error("This history contains no user request. Supply a session with its request context.");
66
+ let normalizedBytes = 0;
67
+ return starts.map((start, position) => {
68
+ const end = starts[position + 1] ?? messages.length;
69
+ const responses = messages.slice(start + 1, end);
70
+ const assistant = responses.filter(message => message.role === "assistant").at(-1);
71
+ const request = messages[start];
72
+ const identity = request.entryId ?? request.message_id ?? request.id ?? contentHash({ start, request });
73
+ const record = {
74
+ id: intakeId(format, [sessionId, identity]), familyKey: intakeId(format, family), split: "train", kind: "attempt",
75
+ input: { request: request.content ?? null, messages: messages.slice(0, start + 1) },
76
+ observedOutput: assistant ? { response: assistant.content ?? null, messages: responses } : null, expected: null,
77
+ sourceId: `${format}:${sessionId}:${String(identity)}`, sourceHash: source.sourceHash,
78
+ occurredAt: intakeDate(assistant?.timestamp ?? request.timestamp), metadata: source.metadata,
79
+ warnings: [...source.warnings, ...(!assistant ? ["No assistant response was recorded for this request."] : [])], needsContext: true,
80
+ };
81
+ assertBoundedTaskJson(record);
82
+ normalizedBytes += new TextEncoder().encode(JSON.stringify(record)).length;
83
+ if (normalizedBytes > TASK_INTAKE_LIMITS.bytes)
84
+ throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");
85
+ return TaskIntakeRecordSchema.parse(record);
86
+ });
87
+ }
@@ -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,14 @@
1
+ /** Preserve the original UTF-8 bytes, including a leading BOM. Binary or invalid
2
+ * UTF-8 input must not silently turn into replacement characters in evidence. */
3
+ export function decodeTaskIntakeText(bytes) {
4
+ try {
5
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
6
+ }
7
+ catch {
8
+ throw new Error("Import files must contain valid UTF-8 text. Binary attachments are not supported by this import format.");
9
+ }
10
+ }
11
+ /** A BOM is a transport marker only at the start of a structured text file. */
12
+ export function structuredIntakeText(text) {
13
+ return text.startsWith("\uFEFF") ? text.slice(1) : text;
14
+ }
@@ -0,0 +1,115 @@
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 { structuredIntakeText } from "./intake-text.js";
8
+ export { decodeTaskIntakeText } from "./intake-text.js";
9
+ import { parseHermesSession, parseOpenClawBundle } from "./intake-history.js";
10
+ import { intakeDate, intakeId, TASK_INTAKE_LIMITS, TaskIntakeFileSchema, TaskIntakeFormatSchema, TaskIntakeRecordSchema, TaskIntakePreviewSchema } from "./intake-contracts.js";
11
+ const taskSchema = z.object({
12
+ instruction: z.string().trim().min(1).max(100_000), context: z.union([z.string(), LearningJsonObjectSchema]).optional(),
13
+ reference: z.union([z.string(), LearningJsonObjectSchema]).optional(), labels: z.union([z.string(), z.array(z.string()), LearningJsonObjectSchema]).optional(),
14
+ id: z.string().min(1).max(200).optional(), familyKey: z.string().min(1).max(200).optional(), split: TaskSplitSchema.optional(),
15
+ }).strict();
16
+ const structuredTaskSchema = z.object({
17
+ input: LearningJsonObjectSchema, observedOutput: LearningJsonObjectSchema.nullable().optional(), expectedOutput: LearningJsonObjectSchema.nullable().optional(),
18
+ id: z.string().min(1).max(200).optional(), familyKey: z.string().min(1).max(200).optional(), split: TaskSplitSchema.optional(),
19
+ occurredAt: z.string().datetime().optional(), labels: LearningJsonObjectSchema.optional(),
20
+ }).strict();
21
+ export function previewTaskIntake(input) {
22
+ const format = TaskIntakeFormatSchema.parse(input.format);
23
+ const files = z.array(TaskIntakeFileSchema).min(1).max(TASK_INTAKE_LIMITS.files).parse(input.files);
24
+ if (files.reduce((size, file) => size + new TextEncoder().encode(file.text).length, 0) > TASK_INTAKE_LIMITS.bytes)
25
+ throw new Error("Import exceeds the 5 MiB size limit.");
26
+ 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)
27
+ throw new Error("Import contains an unsafe or duplicate file path.");
28
+ const records = [], issues = [];
29
+ const seen = new Map();
30
+ const splits = new Map();
31
+ let normalizedBytes = 0;
32
+ function attempt(file, row, parse) {
33
+ try {
34
+ const parsed = parse();
35
+ if (records.length + parsed.length > TASK_INTAKE_LIMITS.records)
36
+ throw new Error("Import exceeds the 1,000-record limit.");
37
+ const nextSeen = new Map(seen), nextSplits = new Map(splits);
38
+ let addedBytes = 0;
39
+ for (const record of parsed) {
40
+ assertBoundedTaskJson(record);
41
+ const hash = contentHash(record);
42
+ const existing = nextSeen.get(record.id);
43
+ if (existing && existing !== hash)
44
+ throw new Error("The same record identity has different content in this upload.");
45
+ if (!existing)
46
+ addedBytes += new TextEncoder().encode(JSON.stringify(record)).length;
47
+ nextSeen.set(record.id, hash);
48
+ for (const key of [`family:${record.familyKey}`, `input:${contentHash(record.input)}`]) {
49
+ if (nextSplits.has(key) && nextSplits.get(key) !== record.split)
50
+ throw new Error("The same task family or request occurs in different splits.");
51
+ nextSplits.set(key, record.split);
52
+ }
53
+ }
54
+ if (normalizedBytes + addedBytes > TASK_INTAKE_LIMITS.bytes * 2)
55
+ throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");
56
+ for (const record of parsed) {
57
+ if (!seen.has(record.id))
58
+ records.push(record);
59
+ seen.set(record.id, contentHash(record));
60
+ }
61
+ for (const [key, split] of nextSplits)
62
+ splits.set(key, split);
63
+ normalizedBytes += addedBytes;
64
+ }
65
+ catch (error) {
66
+ 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." });
67
+ }
68
+ }
69
+ if (format === "openclaw")
70
+ attempt("manifest.json", null, () => parseOpenClawBundle(files));
71
+ else
72
+ for (const file of files) {
73
+ const text = structuredIntakeText(file.text);
74
+ if (format === "jsonl" || format === "hermes") {
75
+ for (const [index, line] of text.split(/\r?\n/u).entries()) {
76
+ if (!line.trim())
77
+ continue;
78
+ if (issues.length >= TASK_INTAKE_LIMITS.records)
79
+ break;
80
+ attempt(file.path, index + 1, () => format === "hermes" ? parseHermesSession(JSON.parse(line)) : [normalizeTask(JSON.parse(line))]);
81
+ }
82
+ }
83
+ else {
84
+ let values;
85
+ try {
86
+ const value = format === "csv" ? parseTaskIntakeCsv(text) : JSON.parse(text);
87
+ values = Array.isArray(value) ? value : [value];
88
+ }
89
+ catch (error) {
90
+ attempt(file.path, null, () => { throw error; });
91
+ continue;
92
+ }
93
+ if (values.length > TASK_INTAKE_LIMITS.records) {
94
+ attempt(file.path, null, () => { throw new Error("Import exceeds the 1,000-record limit."); });
95
+ continue;
96
+ }
97
+ values.forEach((value, index) => attempt(file.path, index + (format === "csv" ? 2 : 1), () => [normalizeTask(value)]));
98
+ }
99
+ }
100
+ return TaskIntakePreviewSchema.parse({ schemaVersion: "openpond.taskIntakePreview.v1", format, contentHash: contentHash({ format, files }), records, issues: issues.slice(0, 1_000) });
101
+ }
102
+ function normalizeTask(value) {
103
+ const parsed = z.union([taskSchema, structuredTaskSchema]).parse(value);
104
+ const simple = "instruction" in parsed;
105
+ const input = simple ? { instruction: parsed.instruction, ...(parsed.context === undefined ? {} : { context: parsed.context }) } : parsed.input;
106
+ const expected = simple ? parsed.reference === undefined ? null : typeof parsed.reference === "string" ? { text: parsed.reference } : parsed.reference : parsed.expectedOutput ?? null;
107
+ const observedOutput = simple ? null : parsed.observedOutput ?? null;
108
+ // Without an explicit family, identical requests stay together even when
109
+ // their imported labels or reference answers differ.
110
+ const familyKey = parsed.familyKey ?? intakeId("family", input);
111
+ const id = parsed.id ?? intakeId("task", { input, expected, observedOutput });
112
+ return TaskIntakeRecordSchema.parse({ id, familyKey, split: parsed.split ?? "train", kind: observedOutput ? "attempt" : "task", input,
113
+ expected, observedOutput, sourceId: id, sourceHash: contentHash(value), occurredAt: simple ? null : intakeDate(parsed.occurredAt),
114
+ metadata: parsed.labels === undefined ? {} : { importedLabels: parsed.labels, labelOrigin: "unverified_import" }, warnings: [], needsContext: false });
115
+ }