@jive-sh/skill-sync 0.7.3 → 0.8.0-latest-darwin-x64
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/multi-call-binary +4 -0
- package/package.json +11 -36
- package/README.md +0 -201
- package/bin/package.json +0 -1
- package/bin/skill-sync +0 -614
- package/bin/skill-sync-daemon +0 -614
- package/dist/daemons/skill-sync-daemon.js +0 -634
- package/dist/daemons/skill-sync-daemon.js.map +0 -1
- package/dist/entrypoints/skill-sync.js +0 -7
- package/dist/entrypoints/skill-sync.js.map +0 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +0 -1
- package/dist/internal/agents/agent-tool.js +0 -102
- package/dist/internal/agents/agent-tool.js.map +0 -1
- package/dist/internal/agents/claude.js +0 -424
- package/dist/internal/agents/claude.js.map +0 -1
- package/dist/internal/agents/codex.js +0 -270
- package/dist/internal/agents/codex.js.map +0 -1
- package/dist/internal/agents/command.js +0 -219
- package/dist/internal/agents/command.js.map +0 -1
- package/dist/internal/agents/grok.js +0 -170
- package/dist/internal/agents/grok.js.map +0 -1
- package/dist/internal/agents/index.js +0 -70
- package/dist/internal/agents/index.js.map +0 -1
- package/dist/internal/cli.js +0 -185
- package/dist/internal/cli.js.map +0 -1
- package/dist/internal/config.js +0 -131
- package/dist/internal/config.js.map +0 -1
- package/dist/internal/control.js +0 -113
- package/dist/internal/control.js.map +0 -1
- package/dist/internal/daemon-control/impl.js +0 -68
- package/dist/internal/daemon-control/impl.js.map +0 -1
- package/dist/internal/daemon-control/interface.js +0 -4
- package/dist/internal/daemon-control/interface.js.map +0 -1
- package/dist/internal/folders.js +0 -47
- package/dist/internal/folders.js.map +0 -1
- package/dist/internal/local-skills.js +0 -43
- package/dist/internal/local-skills.js.map +0 -1
- package/dist/internal/path.js +0 -36
- package/dist/internal/path.js.map +0 -1
- package/dist/internal/server.js +0 -80
- package/dist/internal/server.js.map +0 -1
- package/dist/internal/skill-check.js +0 -83
- package/dist/internal/skill-check.js.map +0 -1
- package/dist/internal/skill-refinement/evals/cases.js +0 -143
- package/dist/internal/skill-refinement/evals/cases.js.map +0 -1
- package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
- package/dist/internal/skill-refinement/evals/opus-judge-original.json +0 -165
- package/dist/internal/skill-refinement/feedback/intake.js +0 -52
- package/dist/internal/skill-refinement/feedback/intake.js.map +0 -1
- package/dist/internal/skill-refinement/jev/impl.js +0 -51
- package/dist/internal/skill-refinement/jev/impl.js.map +0 -1
- package/dist/internal/skill-refinement/jev/interface.js +0 -14
- package/dist/internal/skill-refinement/jev/interface.js.map +0 -1
- package/dist/internal/skill-refinement/paths.js +0 -62
- package/dist/internal/skill-refinement/paths.js.map +0 -1
- package/dist/internal/skill-refinement/platform.js +0 -68
- package/dist/internal/skill-refinement/platform.js.map +0 -1
- package/dist/internal/skill-refinement/service.js +0 -253
- package/dist/internal/skill-refinement/service.js.map +0 -1
- package/dist/internal/skill-refinement/skills/skill-text.js +0 -217
- package/dist/internal/skill-refinement/skills/skill-text.js.map +0 -1
- package/dist/internal/skill-refinement/workflow/retry.js +0 -69
- package/dist/internal/skill-refinement/workflow/retry.js.map +0 -1
- package/dist/internal/skill-refinement/workflow/skill-refinement.js +0 -593
- package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +0 -1
- package/dist/internal/skill-refinement/writer/impl.js +0 -69
- package/dist/internal/skill-refinement/writer/impl.js.map +0 -1
- package/dist/internal/skill-refinement/writer/interface.js +0 -10
- package/dist/internal/skill-refinement/writer/interface.js.map +0 -1
- package/dist/internal/sync.js +0 -182
- package/dist/internal/sync.js.map +0 -1
- package/dist/internal/wire.js +0 -31
- package/dist/internal/wire.js.map +0 -1
- package/install.cjs +0 -614
- package/src/daemons/skill-sync-daemon.ts +0 -639
- package/src/entrypoints/skill-sync.ts +0 -12
- package/src/index.ts +0 -15
- package/src/internal/agents/agent-tool.ts +0 -149
- package/src/internal/agents/claude.ts +0 -442
- package/src/internal/agents/codex.ts +0 -288
- package/src/internal/agents/command.ts +0 -257
- package/src/internal/agents/grok.ts +0 -174
- package/src/internal/agents/index.ts +0 -74
- package/src/internal/cli.ts +0 -217
- package/src/internal/config.ts +0 -172
- package/src/internal/control.ts +0 -157
- package/src/internal/daemon-control/impl.ts +0 -80
- package/src/internal/daemon-control/interface.ts +0 -40
- package/src/internal/folders.ts +0 -50
- package/src/internal/local-skills.ts +0 -58
- package/src/internal/path.ts +0 -32
- package/src/internal/server.ts +0 -76
- package/src/internal/skill-check.ts +0 -97
- package/src/internal/skill-refinement/evals/cases.ts +0 -167
- package/src/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
- package/src/internal/skill-refinement/evals/opus-judge-original.json +0 -165
- package/src/internal/skill-refinement/feedback/intake.ts +0 -66
- package/src/internal/skill-refinement/jev/impl.ts +0 -63
- package/src/internal/skill-refinement/jev/interface.ts +0 -51
- package/src/internal/skill-refinement/paths.ts +0 -87
- package/src/internal/skill-refinement/platform.ts +0 -72
- package/src/internal/skill-refinement/service.ts +0 -299
- package/src/internal/skill-refinement/skills/skill-text.ts +0 -290
- package/src/internal/skill-refinement/workflow/retry.ts +0 -76
- package/src/internal/skill-refinement/workflow/skill-refinement.ts +0 -665
- package/src/internal/skill-refinement/writer/impl.ts +0 -79
- package/src/internal/skill-refinement/writer/interface.ts +0 -29
- package/src/internal/sync.ts +0 -216
- package/src/internal/wire.ts +0 -439
|
@@ -1,665 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SKILL REFINEMENT: ONE RUN PER FEEDBACK ITEM, EACH STEP A FRESH, SMALL CALL.
|
|
3
|
-
*
|
|
4
|
-
* Pick takes the head of the intake's queue.
|
|
5
|
-
* Calibrate judge Jev, the judge of reply cases, grades the original replies Alex objected to (and the one he called
|
|
6
|
-
* good) once per judge version; agreeing with him less often than the Opus judge did ends the run here.
|
|
7
|
-
* Classify Jev names the skill section the item is about, and whether it is new, a repeat or a correction;
|
|
8
|
-
* a section that points to another skill's section for the rule is asked again with those sections.
|
|
9
|
-
* Draft the generative model reads only that skill (with its line budget, where it states a cap), its
|
|
10
|
-
* example names, its rules for changing skills and the item, and writes candidate edits, the item's
|
|
11
|
-
* example and its A/B case. A candidate applies when its edits do, and every sentence it takes out
|
|
12
|
-
* that no synced skill holds after it is still required by its new text, as Jev judges.
|
|
13
|
-
* Choose examples Jev names the section that owns each A/B case's failure; the changed section's cases, and the
|
|
14
|
-
* item's own, are tested.
|
|
15
|
-
* A/B for each chosen case, the generative model writes the reply under the current text and under
|
|
16
|
-
* each candidate, two samples each.
|
|
17
|
-
* Judge each reply goes to its case kind's judge: an action case to the Opus judge, a reply case to Jev;
|
|
18
|
-
* candidates are ranked by their passes.
|
|
19
|
-
* Install the best candidate that fails no case the current text passes is written to the synced skill,
|
|
20
|
-
* rebased on any edit made to it since Draft, then skill-sync's synced list must show the skill
|
|
21
|
-
* edited after the install.
|
|
22
|
-
*
|
|
23
|
-
* With no winner (or no candidate that applies), Draft writes new candidates once more in the same run, reading why each
|
|
24
|
-
* reply failed, against the same case; the current text's replies and verdicts are reused, so only the new candidates
|
|
25
|
-
* are written and judged. Run on 23 past runs (2026-11-19), every run with no winner failed the item's own case under
|
|
26
|
-
* the current text and both candidates alike, most often for a part another rule of the skill requires (a quote of his
|
|
27
|
-
* message, a Blocked on you line), which a change to the one rule the item names cannot fix: those reasons reached Draft
|
|
28
|
-
* only as a note for a next run, and an item whose inputs are unchanged gets none.
|
|
29
|
-
*
|
|
30
|
-
* The content rules (what a good change is) live in the `autonomous-skill-refinement` skill around this code; Draft
|
|
31
|
-
* reads them from it each run. Jev classifies and judges; only Draft and A/B, which must write text, call a generative model.
|
|
32
|
-
*/
|
|
33
|
-
import { AgentStep, RUN_ENDS, RUN_STARTS, A_STEP_FAILS, type WorkflowPlatform } from '@jive-sh/workflow-platform';
|
|
34
|
-
import { Effect, Option, pipe, Result, Schema } from 'effect';
|
|
35
|
-
import fs from 'node:fs';
|
|
36
|
-
import path from 'node:path';
|
|
37
|
-
import { Jev } from '../jev/interface';
|
|
38
|
-
import { Writer, type WriterSpend } from '../writer/interface';
|
|
39
|
-
import { applyEdits, lineBudgetOf, pointedSections, sentencesRemoved, shaOf, SkillFiles, type SkillEdit, type SkillSection } from '../skills/skill-text';
|
|
40
|
-
import { actionJudgePrompt, actionPasses, ActionVerdict, caseSummary, EvalCase, judgeOf, judgeQuestions, judgeState, judgeVersion, nextCaseFile, readCases, REPLY_CRITERIA, verdictOf, writerPrompt, writerSystem } from '../evals/cases';
|
|
41
|
-
import type { Intake } from '../feedback/intake';
|
|
42
|
-
import { evalCasesFolder, runFolder, type WorkflowFolders } from '../paths';
|
|
43
|
-
import { retryAt, retryInput, type Outcome as NotedOutcome } from './retry';
|
|
44
|
-
|
|
45
|
-
export const WORKFLOW = 'Skill refinement';
|
|
46
|
-
/** The skill that owns this process: Draft reads its rules for a good change on each run. */
|
|
47
|
-
export const OWNING_SKILL = 'autonomous-skill-refinement';
|
|
48
|
-
/** Replies written per case and version: one varies too much to decide on (`evals/README.md`). */
|
|
49
|
-
export const SAMPLES = 2;
|
|
50
|
-
/** Candidate edits drafted per item. */
|
|
51
|
-
export const CANDIDATES = 2;
|
|
52
|
-
/** Draft's tries per run: the first, and one more that reads why the first one's replies failed. */
|
|
53
|
-
export const DRAFT_ROUNDS = 2;
|
|
54
|
-
/** Writer calls at once. */
|
|
55
|
-
const WRITERS_AT_ONCE = 4;
|
|
56
|
-
/** Installs per run on the skill's latest text, when an edit lands while one is being written or replaces it afterwards. */
|
|
57
|
-
const INSTALL_TRIES = 3;
|
|
58
|
-
|
|
59
|
-
export interface SkillRefinementDeps {
|
|
60
|
-
readonly platform: WorkflowPlatform<'skills', never>;
|
|
61
|
-
readonly intake: Intake;
|
|
62
|
-
readonly folders: WorkflowFolders;
|
|
63
|
-
/** The Opus judge's grades of the original replies (`evals/opus-judge-original.json`), the bar a new judge must meet. */
|
|
64
|
-
readonly opusJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
|
|
65
|
-
/** The evals' original action-judge prompt's grades of the action originals (`evals/opus-action-judge-original.json`). */
|
|
66
|
-
readonly opusActionJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
|
|
67
|
-
/** What decides a task's inputs beyond its own text: the judge's and writer's versions, and whether Jev is reachable. */
|
|
68
|
-
readonly configFingerprint: () => string;
|
|
69
|
-
/** The time now, unix seconds: when a failed item's retry time has passed (`retry.ts`). */
|
|
70
|
-
readonly now: () => number;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const Classified = Schema.Struct({ skill: Schema.String, section: Schema.String, sectionConfidence: Schema.Finite, kind: Schema.String, kindConfidence: Schema.Finite, jevModel: Schema.String });
|
|
74
|
-
const Drafted = Schema.Struct({
|
|
75
|
-
skill: Schema.String, draftedOn: Schema.String, file: Schema.String,
|
|
76
|
-
candidates: Schema.Array(Schema.Struct({ summary: Schema.String, applies: Schema.Boolean, why: Schema.String })),
|
|
77
|
-
costUsd: Schema.Finite,
|
|
78
|
-
});
|
|
79
|
-
const Chosen = Schema.Struct({ cases: Schema.Array(Schema.String), considered: Schema.Finite });
|
|
80
|
-
const Calibration = Schema.Struct({
|
|
81
|
-
fingerprint: Schema.String, agreed: Schema.Finite, graded: Schema.Finite, opusAgreed: Schema.Finite, opusGraded: Schema.Finite,
|
|
82
|
-
actionAgreed: Schema.Finite, actionGraded: Schema.Finite, actionBaselineAgreed: Schema.Finite, actionBaselineGraded: Schema.Finite,
|
|
83
|
-
usable: Schema.Boolean, file: Schema.String,
|
|
84
|
-
});
|
|
85
|
-
const Replies = Schema.Struct({ file: Schema.String, replies: Schema.Finite, costUsd: Schema.Finite });
|
|
86
|
-
const Ranked = Schema.Struct({
|
|
87
|
-
file: Schema.String,
|
|
88
|
-
versions: Schema.Array(Schema.Struct({ version: Schema.String, passes: Schema.Finite, of: Schema.Finite, score: Schema.Finite, losesTo: Schema.Array(Schema.String) })),
|
|
89
|
-
winner: Schema.NullOr(Schema.Finite),
|
|
90
|
-
why: Schema.String,
|
|
91
|
-
});
|
|
92
|
-
const InstalledStep = Schema.Struct({ skill: Schema.String, wordsBefore: Schema.Finite, wordsAfter: Schema.Finite, files: Schema.Array(Schema.String), rebased: Schema.Boolean, syncListLine: Schema.String });
|
|
93
|
-
export const Outcome = Schema.Struct({ item: Schema.NullOr(Schema.String), outcome: Schema.String, finished: Schema.Boolean });
|
|
94
|
-
export type Outcome = typeof Outcome.Type;
|
|
95
|
-
|
|
96
|
-
/** What Draft writes for one item, as the model returns it. */
|
|
97
|
-
const DraftReply = Schema.Struct({
|
|
98
|
-
candidates: Schema.Array(Schema.Struct({ summary: Schema.String, edits: Schema.Array(Schema.Struct({ find: Schema.String, replace: Schema.String })) })),
|
|
99
|
-
history: Schema.String,
|
|
100
|
-
example: Schema.Struct({ name: Schema.String, text: Schema.String }),
|
|
101
|
-
eval_case: Schema.Struct({ his_question: Schema.String, original_reply: Schema.String, his_reaction: Schema.String, state_before: Schema.Array(Schema.String), wanted: Schema.String, went_wrong: Schema.String }),
|
|
102
|
-
});
|
|
103
|
-
type DraftReply = typeof DraftReply.Type;
|
|
104
|
-
/** What a later round of Draft writes: new candidates for the same case. */
|
|
105
|
-
const RevisedCandidates = Schema.Struct({ candidates: DraftReply.fields.candidates });
|
|
106
|
-
|
|
107
|
-
const jsonIn = (text: string): string => text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1);
|
|
108
|
-
const writeJson = (file: string, value: unknown) => Effect.sync(() => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value, null, 1)); });
|
|
109
|
-
const readJson = <A>(file: string) => Effect.sync(() => JSON.parse(fs.readFileSync(file, 'utf8')) as A);
|
|
110
|
-
|
|
111
|
-
/** Puts one model call's spend on the step's record as it lands. */
|
|
112
|
-
const recordWriterSpend = (id: string, spend: WriterSpend) => Effect.flatMap(AgentStep, (step) => Effect.sync(() => {
|
|
113
|
-
step.usage(id, spend.model, { input_tokens: spend.inputTokens, cache_read_input_tokens: spend.cacheReadTokens, cache_creation_input_tokens: spend.cacheWriteTokens, output_tokens: spend.outputTokens });
|
|
114
|
-
}));
|
|
115
|
-
const recordJevSpend = (id: string, model: string, inputTokens: number, outputTokens: number) => Effect.flatMap(AgentStep, (step) => Effect.sync(() => {
|
|
116
|
-
step.usage(id, model, { input_tokens: inputTokens, output_tokens: outputTokens });
|
|
117
|
-
}));
|
|
118
|
-
|
|
119
|
-
/** How likely Jev must find it that a removed sentence's requirement is still stated, for the change to keep it. */
|
|
120
|
-
const KEPT_REQUIREMENT_CUT = 0.5;
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Whether a drafted candidate may be tested and installed: its edits apply to the skill's text, and every sentence it
|
|
124
|
-
* takes out that no synced skill holds after it is still required by the text that replaced it, as Jev judges. Deleting a
|
|
125
|
-
* rule he set needs his yes (autonomous-skill-refinement § 3 rule 4); on 2026-11-20 a candidate that moved his numbering
|
|
126
|
-
* rule out of senior-swe "with" an edit to agentic-collaboration installed the deletion alone, as a change to one skill does.
|
|
127
|
-
*/
|
|
128
|
-
const checkCandidate = (input: { readonly current: string; readonly elsewhere: string; readonly edits: ReadonlyArray<SkillEdit> }) => Effect.gen(function* () {
|
|
129
|
-
const applied = applyEdits(input.current, input.edits);
|
|
130
|
-
if (Result.isFailure(applied)) return { applies: false, why: applied.failure };
|
|
131
|
-
const removed = sentencesRemoved({ before: input.current, after: applied.success, elsewhere: input.elsewhere });
|
|
132
|
-
if (removed.length === 0) return { applies: true, why: 'applies' };
|
|
133
|
-
const jev = yield* Jev;
|
|
134
|
-
const asked = yield* jev.ask({
|
|
135
|
-
state: { removed_sentences: removed, text_that_replaced_them: input.edits.map((e) => e.replace).join('\n\n') },
|
|
136
|
-
questions: Object.fromEntries(removed.map((sentence, i) => [`kept_${i}`, { type: 'noul' as const, instructions: { question: 'Does the text that replaced them still require what this removed sentence requires?', focus: sentence } }])),
|
|
137
|
-
});
|
|
138
|
-
yield* recordJevSpend('draft kept rules', asked.model, asked.inputTokens, asked.outputTokens);
|
|
139
|
-
const lost = removed.filter((_, i) => (asked.answers[`kept_${i}`] as number) < KEPT_REQUIREMENT_CUT);
|
|
140
|
-
return lost.length === 0
|
|
141
|
-
? { applies: true, why: 'applies' }
|
|
142
|
-
: { applies: false, why: `it deletes a rule no synced skill states after it, which needs his yes: "${lost[0]}"${lost.length > 1 ? ` and ${lost.length - 1} more` : ''}` };
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* The candidates A/B tests: those Draft found may be tested, as edits of the skill's text now, each under the number Draft
|
|
147
|
-
* gave it (`version`), which Judge ranks it by and Install takes the winner by, whichever others stop applying. Pure.
|
|
148
|
-
*/
|
|
149
|
-
const testedVersions = (input: { readonly reply: DraftReply; readonly drafted: typeof Drafted.Type; readonly current: string }) =>
|
|
150
|
-
input.reply.candidates.flatMap((c, i) => {
|
|
151
|
-
if (input.drafted.candidates[i]?.applies !== true) return [];
|
|
152
|
-
const applied = applyEdits(input.current, c.edits);
|
|
153
|
-
return Result.isSuccess(applied) ? [{ candidate: c, version: i + 1, text: applied.success }] : [];
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
/** Every section of the skills as Jev chooses among them: its label, and its opening as what it means. Pure. */
|
|
157
|
-
const sectionCriteria = (sections: ReadonlyArray<{ readonly label: string; readonly text: string }>) => Object.fromEntries(sections.map((x) => [x.label, x.text.slice(0, 600)]));
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* WHERE AN ITEM GOES: the skill whose sections Jev gives the most probability in all, then that skill's likeliest section.
|
|
161
|
-
* Taking the single likeliest section put the convention-over-configuration item (how jive lays out packages) in effect's
|
|
162
|
-
* "Which conventions win" at 0.17, by the word the two share, while senior-swe's sections held 0.53 in all. Measured on 10
|
|
163
|
-
* items whose skill was known (2026-11-16): the same skill as the single likeliest section on the other 9; asking for the
|
|
164
|
-
* skill first, from each skill's description and opening, got 8 of 10. Pure.
|
|
165
|
-
*/
|
|
166
|
-
export const placeBySkill = (input: { readonly probabilities: Readonly<Record<string, number>>; readonly sections: ReadonlyArray<SkillSection> }) => {
|
|
167
|
-
const skillOf = new Map(input.sections.map((x) => [x.label, x.skill]));
|
|
168
|
-
const perSkill = new Map<string, number>();
|
|
169
|
-
for (const [label, p] of Object.entries(input.probabilities)) { const skill = skillOf.get(label); if (skill !== undefined) perSkill.set(skill, (perSkill.get(skill) ?? 0) + p); }
|
|
170
|
-
const [skill, skillProbability] = [...perSkill].sort((a, b) => b[1] - a[1])[0]!;
|
|
171
|
-
const [section, sectionProbability] = Object.entries(input.probabilities).filter(([label]) => skillOf.get(label) === skill).sort((a, b) => b[1] - a[1])[0]!;
|
|
172
|
-
return { skill, skillProbability, section, sectionProbability };
|
|
173
|
-
};
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* The skill's line budget, for a skill that states a cap: told to Draft before it writes, since a candidate over the cap
|
|
177
|
-
* is refused after it (every jive item ended "no candidate applies: the skill would have 218 lines, over its own cap of
|
|
178
|
-
* 200", the skill already at 201). Pure.
|
|
179
|
-
*/
|
|
180
|
-
const lineBudgetLine = (text: string): string => {
|
|
181
|
-
const budget = lineBudgetOf(text);
|
|
182
|
-
if (budget === null) return '';
|
|
183
|
-
return `The skill has ${budget.lines} lines and states its own cap of ${budget.cap}${budget.lines >= budget.cap ? ', so it has no room for a line more' : ''}. A candidate that leaves it over ${budget.cap} lines is refused: one that would go over compacts the skill in the same edits, the way the skill's own rule for its length says.`;
|
|
184
|
-
};
|
|
185
|
-
|
|
186
|
-
/** What Draft writes candidates from: the item, where Jev placed it, and the skill it changes. */
|
|
187
|
-
export interface DraftInput {
|
|
188
|
-
readonly itemText: string;
|
|
189
|
-
readonly section: string;
|
|
190
|
-
readonly sectionConfidence: number;
|
|
191
|
-
readonly kind: string;
|
|
192
|
-
/** Earlier runs' outcomes on this item, as the platform keeps them for the next agent; empty for none. */
|
|
193
|
-
readonly notes: string;
|
|
194
|
-
readonly examples: ReadonlyArray<string>;
|
|
195
|
-
readonly skill: string;
|
|
196
|
-
readonly skillText: string;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Draft's system prompt: the rules for changing skills, from the skill that owns them. Pure. */
|
|
200
|
-
export const draftSystem = (howToChange: string): string =>
|
|
201
|
-
`You maintain Alex's skills: the rules every agent working for him loads. You change one skill's text for one piece of his feedback. These are the rules for changing skills, from the skill that owns them (${OWNING_SKILL}):\n\n${howToChange}`;
|
|
202
|
-
|
|
203
|
-
const draftContext = (input: DraftInput): ReadonlyArray<string> => [
|
|
204
|
-
`The feedback item, as the agent that received it handed it over:\n${input.itemText}`,
|
|
205
|
-
`Jev classified it as about "${input.section}" (confidence ${input.sectionConfidence.toFixed(2)}), kind: ${input.kind}.`,
|
|
206
|
-
input.notes.length > 0 ? `Earlier tries on this item, and why they ended:\n${input.notes}` : '',
|
|
207
|
-
`The skill's example files, by name: ${input.examples.join(', ')}`,
|
|
208
|
-
`The skill ${input.skill}'s whole text now:\n<<<SKILL\n${input.skillText}\nSKILL>>>`,
|
|
209
|
-
lineBudgetLine(input.skillText),
|
|
210
|
-
];
|
|
211
|
-
|
|
212
|
-
const CANDIDATE_JSON = '{"summary": "the rule change in one sentence", "edits": [{"find": "...", "replace": "..."}]}';
|
|
213
|
-
const EDITS_ASKED = 'each a list of exact replacements in that text: "find" must be copied exactly from the text and occur once.';
|
|
214
|
-
|
|
215
|
-
/** Draft's first prompt for an item: candidates, the history entry, the example and the item's A/B case. Pure. */
|
|
216
|
-
export const draftPrompt = (input: DraftInput): string => [
|
|
217
|
-
...draftContext(input),
|
|
218
|
-
`Write ${CANDIDATES} different candidate changes, ${EDITS_ASKED}`
|
|
219
|
-
+ ' Also write the history entry for history.md (a "## " heading naming the rule, then his words, the date and what drew them), the example file (name and text: what happened, his words, why), and the A/B case for this instance as an action case.',
|
|
220
|
-
`Return only JSON: {"candidates": [${CANDIDATE_JSON}], "history": "...", "example": {"name": "topic-words.md", "text": "..."}, "eval_case": {"his_question": "his message that the agent acted on", "original_reply": "what the agent did and said", "his_reaction": "his exact words", "state_before": ["fact"], "wanted": "...", "went_wrong": "..."}}`,
|
|
221
|
-
].filter(Boolean).join('\n\n');
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Draft's next prompt in a run whose candidates did not win: the same item and case, the candidates tried, and why each
|
|
225
|
-
* reply failed, for new candidates only; the case stays as the first round wrote it, so a candidate is never measured
|
|
226
|
-
* against an easier one. Pure.
|
|
227
|
-
*/
|
|
228
|
-
export const reviseDraftPrompt = (input: DraftInput & {
|
|
229
|
-
readonly evalCase: DraftReply['eval_case'];
|
|
230
|
-
readonly tried: ReadonlyArray<{ readonly summary: string; readonly why: string }>;
|
|
231
|
-
readonly whyNoneWon: string;
|
|
232
|
-
}): string => [
|
|
233
|
-
...draftContext(input),
|
|
234
|
-
`The A/B case every candidate is tested on, which a winner must pass:\n${JSON.stringify(input.evalCase, null, 1)}`,
|
|
235
|
-
`The candidates already tried for this item:\n${input.tried.map((t, i) => `${i + 1}. ${t.summary} (${t.why})`).join('\n')}`,
|
|
236
|
-
`Why none of them won: ${input.whyNoneWon}`,
|
|
237
|
-
'Each failure above is a judge\'s reason for one reply written under one version of the skill: the current text or a candidate. A failure every version shares comes from text they all keep, which can be a rule other than the one the feedback names.'
|
|
238
|
-
+ ` Find the rules in the skill text that produce the failures, and write ${CANDIDATES} new candidate changes that remove them, ${EDITS_ASKED}`
|
|
239
|
-
+ ' A candidate never drops or weakens a requirement he stated (the rules for changing skills); where passing the case would need that, its summary names the rule and his words that stand in the way.',
|
|
240
|
-
`Return only JSON: {"candidates": [${CANDIDATE_JSON}]}`,
|
|
241
|
-
].filter(Boolean).join('\n\n');
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Draft's version: its prompts on fixed inputs, and the counts a run tests with. With the judge's version and the skills'
|
|
245
|
-
* text it decides when an item that ended without an install runs again (`configFingerprint`). Pure.
|
|
246
|
-
*/
|
|
247
|
-
export const draftVersion = (): string => {
|
|
248
|
-
const fixed: DraftInput = { itemText: '', section: '', sectionConfidence: 0, kind: '', notes: '', examples: [], skill: '', skillText: '' };
|
|
249
|
-
return JSON.stringify({
|
|
250
|
-
system: draftSystem(''), first: draftPrompt(fixed),
|
|
251
|
-
revise: reviseDraftPrompt({ ...fixed, evalCase: { his_question: '', original_reply: '', his_reaction: '', state_before: [], wanted: '', went_wrong: '' }, tried: [], whyNoneWon: '' }),
|
|
252
|
-
CANDIDATES, SAMPLES, DRAFT_ROUNDS,
|
|
253
|
-
});
|
|
254
|
-
};
|
|
255
|
-
|
|
256
|
-
/** A round's file in the run folder: the first round's keeps its plain name. Pure. */
|
|
257
|
-
const roundFile = (name: string, round: number): string => (round === 1 ? `${name}.json` : `${name}-${round}.json`);
|
|
258
|
-
|
|
259
|
-
/** What calibration measured, in a line: each judge against its baseline. Pure. */
|
|
260
|
-
const calibrationLine = (c: typeof Calibration.Type) => `Jev agrees with Alex on ${c.agreed} of ${c.graded} original replies (Opus judge: ${c.opusAgreed} of ${c.opusGraded}); the action judge fails ${c.actionAgreed} of ${c.actionGraded} action originals he objected to (original prompt: ${c.actionBaselineAgreed} of ${c.actionBaselineGraded})`;
|
|
261
|
-
|
|
262
|
-
export const defineSkillRefinement = (deps: SkillRefinementDeps) => {
|
|
263
|
-
const { defineStep, defineWorkflow, queueNow } = deps.platform.steps;
|
|
264
|
-
const at = import.meta.path;
|
|
265
|
-
|
|
266
|
-
const PICK = defineStep({ name: 'Pick', agent: false, at, description: 'Takes the head of the intake queue.', success: Schema.Option(Schema.String), subject: (o) => Option.getOrNull(o), picked: Option.isSome });
|
|
267
|
-
const CLASSIFY = defineStep({ name: 'Classify', agent: true, at, description: 'Jev names the skill section the item is about, and whether it is new, a repeat or a correction.', success: Classified, reason: (c) => `${c.section} (${c.kind})` });
|
|
268
|
-
const DRAFT = defineStep({ name: 'Draft', agent: true, at, description: 'The generative model drafts candidate edits from the target skill, its example names and the item.', success: Drafted, reason: (d) => `${d.candidates.filter((c) => c.applies).length} of ${d.candidates.length} candidates apply` });
|
|
269
|
-
const CHOOSE = defineStep({ name: 'Choose examples', agent: true, at, description: 'Jev names the section that owns each A/B case; the cases the changed section owns are tested.', success: Chosen, reason: (c) => `${c.cases.length} of ${c.considered} cases` });
|
|
270
|
-
const CALIBRATE = defineStep({ name: 'Calibrate judge', agent: true, shared: true, at, description: 'Once per judge version: Jev grades the original reply cases and the Opus judge the action originals; a judge below its baseline is not used.', success: Calibration, reason: (c) => calibrationLine(c) });
|
|
271
|
-
const AB = defineStep({ name: 'A/B', agent: true, at, description: 'The generative model writes each chosen case under the current text and each candidate.', success: Replies, reason: (r) => `${r.replies} replies, $${r.costUsd.toFixed(2)}` });
|
|
272
|
-
const JUDGE = defineStep({ name: 'Judge', agent: true, at, description: 'Each reply is judged by its case kind\'s judge (an action case by the Opus judge, a reply case by Jev), and the candidates are ranked.', success: Ranked, reason: (r) => r.why });
|
|
273
|
-
const INSTALL = defineStep({ name: 'Install', agent: true, at, description: 'Writes the winner to the synced skill, rebased on any edit made since Draft (Jev re-checks a rebased change for deleted rules), and checks that the synced list shows it.', success: InstalledStep, writes: [], reason: (i) => i.syncListLine });
|
|
274
|
-
|
|
275
|
-
/** Pick: the queue's head, the platform's order. */
|
|
276
|
-
const pick = (run: string) => Effect.map(queueNow({ workflow: WORKFLOW, run }), (queue) => Option.fromNullishOr(queue[0]?.ref.item));
|
|
277
|
-
|
|
278
|
-
const classify = (item: string) => Effect.gen(function* () {
|
|
279
|
-
const jev = yield* Jev;
|
|
280
|
-
const text = yield* deps.intake.text(item);
|
|
281
|
-
const sections = yield* (yield* SkillFiles).sections();
|
|
282
|
-
const where = yield* jev.ask({
|
|
283
|
-
state: { feedback_item: text },
|
|
284
|
-
questions: { section: { type: 'choice', instructions: 'Which section of the skills is the rule this feedback is about, the one a change for it would edit?', criteria: sectionCriteria(sections) } },
|
|
285
|
-
});
|
|
286
|
-
yield* recordJevSpend('classify section', where.model, where.inputTokens, where.outputTokens);
|
|
287
|
-
const placed = placeBySkill({ probabilities: where.answers.section.probabilities, sections });
|
|
288
|
-
const placedSection = sections.find((s) => s.label === placed.section)!;
|
|
289
|
-
// A section that points to another skill's section for a rule does not hold it: Jev chooses again among it and those.
|
|
290
|
-
const pointed = pointedSections(placedSection, sections);
|
|
291
|
-
const holder = pointed.length === 0 ? null : yield* jev.ask({
|
|
292
|
-
state: { feedback_item: text },
|
|
293
|
-
questions: { section: { type: 'choice', instructions: 'Which of these sections holds the rule this feedback is about, the one a change for it would edit? A section that only points to another skill\'s section for the rule does not hold it.', criteria: sectionCriteria([placedSection, ...pointed]) } },
|
|
294
|
-
});
|
|
295
|
-
if (holder !== null) yield* recordJevSpend('classify pointed section', holder.model, holder.inputTokens, holder.outputTokens);
|
|
296
|
-
const section = holder === null ? placedSection : sections.find((s) => s.label === holder.answers.section.choice)!;
|
|
297
|
-
const sectionConfidence = holder === null ? placed.sectionProbability : holder.answers.section.confidence;
|
|
298
|
-
const kind = yield* jev.ask({
|
|
299
|
-
state: { feedback_item: text, the_section_now: section.text },
|
|
300
|
-
questions: { kind: { type: 'choice', instructions: 'What is this feedback, against the section as it reads now?', criteria: {
|
|
301
|
-
new: 'The section has no rule covering what he objects to.',
|
|
302
|
-
repeat: 'The section already has a rule covering it, and the agent broke it again.',
|
|
303
|
-
correction: 'It corrects an earlier feedback item, or a rule saved for one (a wording, a mechanism added to his words).',
|
|
304
|
-
} } },
|
|
305
|
-
});
|
|
306
|
-
yield* recordJevSpend('classify kind', kind.model, kind.inputTokens, kind.outputTokens);
|
|
307
|
-
return { skill: section.skill, section: section.label, sectionConfidence, kind: kind.answers.kind.choice, kindConfidence: kind.answers.kind.confidence, jevModel: kind.model };
|
|
308
|
-
});
|
|
309
|
-
|
|
310
|
-
/**
|
|
311
|
-
* Draft for one round. The first writes the candidates, history entry, example and case; a later one, given the round
|
|
312
|
-
* before it, writes new candidates only, keeping that round's history, example and case.
|
|
313
|
-
*/
|
|
314
|
-
const draft = (input: {
|
|
315
|
-
readonly item: string; readonly run: string; readonly classified: typeof Classified.Type; readonly round: number;
|
|
316
|
-
readonly previous: { readonly drafted: typeof Drafted.Type; readonly whyNoneWon: string } | null;
|
|
317
|
-
}) => Effect.gen(function* () {
|
|
318
|
-
const files = yield* SkillFiles;
|
|
319
|
-
const writer = yield* Writer;
|
|
320
|
-
const target = yield* files.skillText(input.classified.skill);
|
|
321
|
-
const howToChange = (yield* files.skillText(OWNING_SKILL)).text;
|
|
322
|
-
const context: DraftInput = {
|
|
323
|
-
itemText: yield* deps.intake.text(input.item),
|
|
324
|
-
section: input.classified.section, sectionConfidence: input.classified.sectionConfidence, kind: input.classified.kind,
|
|
325
|
-
notes: yield* Effect.orElseSucceed(deps.platform.tasks.notesForAgent({ workflow: WORKFLOW, item: input.item }), () => ''),
|
|
326
|
-
examples: yield* files.exampleNames(input.classified.skill),
|
|
327
|
-
skill: input.classified.skill, skillText: target.text,
|
|
328
|
-
};
|
|
329
|
-
const earlier = input.previous === null ? null : { ...input.previous, reply: yield* readJson<DraftReply>(input.previous.drafted.file) };
|
|
330
|
-
const written = yield* writer.write({
|
|
331
|
-
system: draftSystem(howToChange),
|
|
332
|
-
prompt: earlier === null
|
|
333
|
-
? draftPrompt(context)
|
|
334
|
-
: reviseDraftPrompt({ ...context, evalCase: earlier.reply.eval_case, tried: earlier.drafted.candidates, whyNoneWon: earlier.whyNoneWon }),
|
|
335
|
-
});
|
|
336
|
-
yield* recordWriterSpend(input.round === 1 ? 'draft' : `draft ${input.round}`, written.spend);
|
|
337
|
-
const reply: DraftReply = earlier === null
|
|
338
|
-
? yield* Effect.mapError(Schema.decodeUnknownEffect(Schema.fromJsonString(DraftReply))(jsonIn(written.text)), (e) => `the draft was not the JSON asked for: ${e.message}`)
|
|
339
|
-
: { ...earlier.reply, candidates: (yield* Effect.mapError(Schema.decodeUnknownEffect(Schema.fromJsonString(RevisedCandidates))(jsonIn(written.text)), (e) => `round ${input.round}'s draft was not the JSON asked for: ${e.message}`)).candidates };
|
|
340
|
-
const elsewhere = (yield* files.sections()).filter((x) => x.skill !== input.classified.skill).map((x) => x.text).join('\n');
|
|
341
|
-
const file = path.join(runFolder(deps.folders, input.run), roundFile('draft', input.round));
|
|
342
|
-
yield* writeJson(file, { ...reply, skill: input.classified.skill, draftedOn: target.sha, raw: written.text });
|
|
343
|
-
return {
|
|
344
|
-
skill: input.classified.skill, draftedOn: target.sha, file, costUsd: written.spend.costUsd,
|
|
345
|
-
candidates: yield* Effect.forEach(reply.candidates, (c) => Effect.map(checkCandidate({ current: target.text, elsewhere, edits: c.edits }), (checked) => ({ summary: c.summary, ...checked }))),
|
|
346
|
-
};
|
|
347
|
-
});
|
|
348
|
-
|
|
349
|
-
/** The item's own case, as Draft wrote it, under the id it gets when installed. */
|
|
350
|
-
const itemCase = (reply: DraftReply, id: string): typeof EvalCase.Type => ({
|
|
351
|
-
id, kind: 'action', his_question: reply.eval_case.his_question, original_reply: reply.eval_case.original_reply, his_reaction: reply.eval_case.his_reaction,
|
|
352
|
-
action: { state_before: reply.eval_case.state_before, wanted: reply.eval_case.wanted, went_wrong: reply.eval_case.went_wrong },
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
/**
|
|
356
|
-
* THE EXAMPLES OF THE CHANGED RULE: the cases whose failure Jev places in the section the item changes, asked as Classify
|
|
357
|
-
* asks (one section of all the skills' sections owns each failure), plus the item's own. Asked as "does this rule
|
|
358
|
-
* govern it?", Jev said yes to 51 of 102 cases for one rule (2026-11-16), which would have cost about $21 of A/B for
|
|
359
|
-
* one item. Each case's section is kept per case text and skills version, so it is asked once.
|
|
360
|
-
*/
|
|
361
|
-
const choose = (classified: typeof Classified.Type) => Effect.gen(function* () {
|
|
362
|
-
const jev = yield* Jev;
|
|
363
|
-
const sections = yield* (yield* SkillFiles).sections();
|
|
364
|
-
const criteria = sectionCriteria(sections);
|
|
365
|
-
const version = shaOf(JSON.stringify(criteria));
|
|
366
|
-
const cases = yield* readCases(evalCasesFolder(deps.folders));
|
|
367
|
-
const owners = yield* Effect.forEach(cases, (c) => Effect.gen(function* () {
|
|
368
|
-
const file = path.join(deps.folders.local, 'case-sections', `${shaOf(JSON.stringify(c))}-${version}.json`);
|
|
369
|
-
if (fs.existsSync(file)) return { id: c.id, section: (yield* readJson<{ readonly section: string }>(file)).section };
|
|
370
|
-
const asked = yield* jev.ask({ state: { example: caseSummary(c) }, questions: { section: { type: 'choice', instructions: 'Which section of the skills holds the rule whose breaking this example shows?', criteria } } });
|
|
371
|
-
yield* recordJevSpend(`choose ${c.id}`, asked.model, asked.inputTokens, asked.outputTokens);
|
|
372
|
-
yield* writeJson(file, { case: c.id, section: asked.answers.section.choice, confidence: asked.answers.section.confidence });
|
|
373
|
-
return { id: c.id, section: asked.answers.section.choice };
|
|
374
|
-
}), { concurrency: 8 });
|
|
375
|
-
return { cases: owners.filter((o) => o.section === classified.section).map((o) => o.id), considered: cases.length };
|
|
376
|
-
});
|
|
377
|
-
|
|
378
|
-
/** The judge's version: its questions, the rule that scores them, and the cases it is calibrated on. */
|
|
379
|
-
const judgeFingerprint = (cases: ReadonlyArray<typeof EvalCase.Type>, model: string) => shaOf(JSON.stringify({ judge: judgeVersion(), model, cases: cases.map((c) => [c.id, c.original_reply]) }));
|
|
380
|
-
|
|
381
|
-
/** The Opus judge's grade of one plan and reply for an action case, its spend on the step's record. */
|
|
382
|
-
const opusGrade = (input: { readonly id: string; readonly c: typeof EvalCase.Type; readonly reply: string }) => Effect.gen(function* () {
|
|
383
|
-
const graded = yield* (yield* Writer).write({ system: 'You grade one agent\'s plan and reply. Return only the JSON asked for.', prompt: actionJudgePrompt(input.c, input.reply) });
|
|
384
|
-
yield* recordWriterSpend(input.id, graded.spend);
|
|
385
|
-
return yield* Effect.mapError(Schema.decodeUnknownEffect(Schema.fromJsonString(ActionVerdict))(jsonIn(graded.text)), (e) => `the Opus judge's verdict on ${input.c.id} was not the JSON asked for: ${e.message}`);
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
/**
|
|
389
|
-
* BOTH JUDGES ARE HELD TO A BAR BEFORE ANY ITEM'S MODEL CALL, once per judge version. Jev, the judge of reply cases, must
|
|
390
|
-
* agree with Alex on the original replies at least as often as the Opus judge did; the Opus judge of action cases must
|
|
391
|
-
* fail at least as many of the action originals he objected to (all of them) as the evals' original action-judge prompt
|
|
392
|
-
* did, so a change to its prompt never makes it more lenient on what he rejected.
|
|
393
|
-
*/
|
|
394
|
-
const calibrate = () => Effect.gen(function* () {
|
|
395
|
-
const jev = yield* Jev;
|
|
396
|
-
const all = yield* readCases(evalCasesFolder(deps.folders));
|
|
397
|
-
const replyCases = new Set(all.filter((c) => judgeOf(c) === 'jev').map((c) => c.id));
|
|
398
|
-
const opus = deps.opusJudgeGrades.filter((o) => replyCases.has(o.case));
|
|
399
|
-
const actionBaseline = deps.opusActionJudgeGrades;
|
|
400
|
-
// With no grade to compare against, the bar would be zero and any judge would pass it.
|
|
401
|
-
if (opus.length === 0 || actionBaseline.length === 0) return yield* Effect.fail('the Opus judge has no baseline grades, so no judge can be held to them');
|
|
402
|
-
const graded = new Set(opus.map((o) => o.case));
|
|
403
|
-
const cases = all.filter((c) => graded.has(c.id));
|
|
404
|
-
const actionIds = new Set(actionBaseline.map((o) => o.case));
|
|
405
|
-
const actionCases = all.filter((c) => actionIds.has(c.id));
|
|
406
|
-
const fingerprint = judgeFingerprint([...cases, ...actionCases], 'jev-latest');
|
|
407
|
-
const file = path.join(deps.folders.local, 'judge-calibration', `${fingerprint}.json`);
|
|
408
|
-
if (fs.existsSync(file)) return yield* readJson<typeof Calibration.Type>(file);
|
|
409
|
-
// He objected to every original reply but the ones he labelled good: a judge agrees with him when it fails those and passes these.
|
|
410
|
-
const wanted = (id: string) => id.startsWith('good-');
|
|
411
|
-
const verdicts = yield* Effect.forEach(cases, (c) => Effect.gen(function* () { const a = yield* jev.ask({ state: judgeState(c, c.original_reply), questions: judgeQuestions() }); return { id: c.id, a, verdict: verdictOf(a.answers as Record<string, number>) }; }), { concurrency: 8 });
|
|
412
|
-
for (const v of verdicts) yield* recordJevSpend(`calibrate ${v.id}`, v.a.model, v.a.inputTokens, v.a.outputTokens);
|
|
413
|
-
const agreed = verdicts.filter((v) => v.verdict.pass === wanted(v.id)).length;
|
|
414
|
-
const opusAgreed = opus.filter((o) => o.pass === wanted(o.case)).length;
|
|
415
|
-
const actions = yield* Effect.forEach(actionCases, (c) => Effect.map(opusGrade({ id: `calibrate ${c.id}`, c, reply: c.original_reply }), (v) => ({ id: c.id, pass: actionPasses(v), why: v.why })), { concurrency: WRITERS_AT_ONCE });
|
|
416
|
-
const actionAgreed = actions.filter((a) => !a.pass).length;
|
|
417
|
-
const actionBaselineAgreed = actionBaseline.filter((o) => !o.pass).length;
|
|
418
|
-
const result = {
|
|
419
|
-
fingerprint, agreed, graded: verdicts.length, opusAgreed, opusGraded: opus.length,
|
|
420
|
-
actionAgreed, actionGraded: actions.length, actionBaselineAgreed, actionBaselineGraded: actionBaseline.length,
|
|
421
|
-
usable: verdicts.length > 0 && agreed / verdicts.length >= opusAgreed / opus.length && actionAgreed / actions.length >= actionBaselineAgreed / actionBaseline.length,
|
|
422
|
-
file,
|
|
423
|
-
};
|
|
424
|
-
yield* writeJson(file, { ...result, verdicts: verdicts.map((v) => ({ id: v.id, ...v.a.answers, ...v.verdict })), actions });
|
|
425
|
-
return result;
|
|
426
|
-
});
|
|
427
|
-
|
|
428
|
-
/** Every (case, version, sample) to write: version 0 is the current text, then each candidate that applies under its number from Draft. */
|
|
429
|
-
const abJobs = (input: { readonly reply: DraftReply; readonly drafted: typeof Drafted.Type; readonly current: string; readonly cases: ReadonlyArray<typeof EvalCase.Type> }) => {
|
|
430
|
-
const versions = [{ version: 0, text: input.current }, ...testedVersions(input)];
|
|
431
|
-
return input.cases.flatMap((c) => versions.flatMap(({ version, text }) => Array.from({ length: SAMPLES }, (_, sample) => ({ c, version, text, sample }))));
|
|
432
|
-
};
|
|
433
|
-
|
|
434
|
-
type WrittenReply = { readonly case: typeof EvalCase.Type; readonly version: number; readonly sample: number; readonly reply: string; readonly costUsd: number };
|
|
435
|
-
|
|
436
|
-
/** A/B for one round; given an earlier round's replies, the current text's are taken from them, not written again. */
|
|
437
|
-
const ab = (input: { readonly run: string; readonly drafted: typeof Drafted.Type; readonly chosen: typeof Chosen.Type; readonly item: string; readonly round: number; readonly currentTextReplies: string | null }) => Effect.gen(function* () {
|
|
438
|
-
const writer = yield* Writer;
|
|
439
|
-
const reply = yield* readJson<DraftReply>(input.drafted.file);
|
|
440
|
-
const current = (yield* (yield* SkillFiles).skillText(input.drafted.skill)).text;
|
|
441
|
-
const all = yield* readCases(evalCasesFolder(deps.folders));
|
|
442
|
-
const cases = [...all.filter((c) => input.chosen.cases.includes(c.id)), itemCase(reply, `this item (${input.item})`)];
|
|
443
|
-
const reused = input.currentTextReplies === null ? [] : (yield* readJson<ReadonlyArray<WrittenReply>>(input.currentTextReplies)).filter((w) => w.version === 0);
|
|
444
|
-
const jobs = abJobs({ reply, drafted: input.drafted, current, cases }).filter((j) => reused.length === 0 || j.version !== 0);
|
|
445
|
-
const written = yield* Effect.forEach(jobs, (j) => Effect.gen(function* () {
|
|
446
|
-
const w = yield* writer.write({ system: writerSystem(input.drafted.skill, j.text), prompt: writerPrompt(j.c) });
|
|
447
|
-
yield* recordWriterSpend(`${input.round === 1 ? '' : `round ${input.round} `}${j.c.id} v${j.version} s${j.sample}`, w.spend);
|
|
448
|
-
return { case: j.c, version: j.version, sample: j.sample, reply: w.text, costUsd: w.spend.costUsd };
|
|
449
|
-
}), { concurrency: WRITERS_AT_ONCE });
|
|
450
|
-
const file = path.join(runFolder(deps.folders, input.run), roundFile('replies', input.round));
|
|
451
|
-
yield* writeJson(file, [...reused, ...written]);
|
|
452
|
-
return { file, replies: written.length, costUsd: written.reduce((s, w) => s + w.costUsd, 0) };
|
|
453
|
-
});
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* Ranks the versions by passes. A candidate wins only if it fails no case the current text passes (a case passes for a
|
|
457
|
-
* version when most of its samples pass) and passes the item's own case; of those, the most passes wins.
|
|
458
|
-
*/
|
|
459
|
-
const judge = (input: { readonly run: string; readonly replies: typeof Replies.Type; readonly round: number; readonly currentTextVerdicts: string | null }) => Effect.gen(function* () {
|
|
460
|
-
const jev = yield* Jev;
|
|
461
|
-
const written = yield* readJson<ReadonlyArray<WrittenReply>>(input.replies.file);
|
|
462
|
-
// An earlier round's verdicts on the current text's replies stand: those replies are the same ones.
|
|
463
|
-
const reused = input.currentTextVerdicts === null ? [] : (yield* readJson<{ readonly judged: ReadonlyArray<Judged> }>(input.currentTextVerdicts)).judged.filter((j) => j.version === 0);
|
|
464
|
-
const fresh = yield* Effect.forEach(written.filter((w) => reused.length === 0 || w.version !== 0), (w) => Effect.gen(function* () {
|
|
465
|
-
const id = `judge ${input.round === 1 ? '' : `round ${input.round} `}${w.case.id} v${w.version} s${w.sample}`;
|
|
466
|
-
// Each case goes to its kind's judge (`judgeOf`): an action case to the Opus judge, a reply case to Jev.
|
|
467
|
-
if (judgeOf(w.case) === 'opus') {
|
|
468
|
-
const verdict = yield* opusGrade({ id, c: w.case, reply: w.reply });
|
|
469
|
-
return { caseId: w.case.id, version: w.version, sample: w.sample, judge: 'opus' as const, verdict, pass: actionPasses(verdict), score: actionPasses(verdict) ? 1 : 0 };
|
|
470
|
-
}
|
|
471
|
-
const a = yield* jev.ask({ state: judgeState(w.case, w.reply), questions: judgeQuestions() });
|
|
472
|
-
yield* recordJevSpend(id, a.model, a.inputTokens, a.outputTokens);
|
|
473
|
-
return { caseId: w.case.id, version: w.version, sample: w.sample, judge: 'jev' as const, answers: a.answers, ...verdictOf(a.answers as Record<string, number>) };
|
|
474
|
-
}), { concurrency: WRITERS_AT_ONCE });
|
|
475
|
-
const judged = [...reused, ...fresh];
|
|
476
|
-
const ranked = rank(judged);
|
|
477
|
-
const file = path.join(runFolder(deps.folders, input.run), roundFile('judged', input.round));
|
|
478
|
-
yield* writeJson(file, { judged, ranked });
|
|
479
|
-
// The outcome note the next Draft of this item reads: with no winner, why each failing reply failed, so it can aim there.
|
|
480
|
-
const failures = failureReasons(judged);
|
|
481
|
-
const why = ranked.winner === null && failures.length > 0 ? `${ranked.why}. Why replies failed: ${failures.join(' | ')}` : ranked.why;
|
|
482
|
-
return { file, ...ranked, why };
|
|
483
|
-
});
|
|
484
|
-
|
|
485
|
-
/**
|
|
486
|
-
* Installs the winner on the skill's text as it is now, which may hold edits made since Draft read it (here, or pulled
|
|
487
|
-
* from another machine): the winner's exact replacements are applied to that text, so every edit outside the lines it
|
|
488
|
-
* replaces is kept. On rebased text the rule-deletion check runs again. An edit landing during the install, or one from
|
|
489
|
-
* another machine replacing it afterwards, rebases it again, up to `INSTALL_TRIES` times. A winner whose lines another
|
|
490
|
-
* edit has changed no longer applies, and the item's next run drafts on the new text.
|
|
491
|
-
*/
|
|
492
|
-
const install = (input: { readonly item: string; readonly run: string; readonly drafted: typeof Drafted.Type; readonly winner: number }) => Effect.gen(function* () {
|
|
493
|
-
const files = yield* SkillFiles;
|
|
494
|
-
const reply = yield* readJson<DraftReply>(input.drafted.file);
|
|
495
|
-
const winner = reply.candidates[input.winner - 1];
|
|
496
|
-
if (winner === undefined) return yield* Effect.fail(`Draft wrote no candidate ${input.winner}`);
|
|
497
|
-
// Chosen once, so a retry rewrites this case instead of taking the next free number.
|
|
498
|
-
const caseFile = nextCaseFile(fs.readdirSync(evalCasesFolder(deps.folders)));
|
|
499
|
-
const evalCase = itemCase(reply, caseFile.replace(/\.json$/, ''));
|
|
500
|
-
for (let tries = 1; ; tries++) {
|
|
501
|
-
const current = yield* files.skillText(input.drafted.skill);
|
|
502
|
-
const rebased = current.sha !== input.drafted.draftedOn;
|
|
503
|
-
const applied = rebased
|
|
504
|
-
? yield* checkCandidate({ current: current.text, elsewhere: (yield* files.sections()).filter((x) => x.skill !== input.drafted.skill).map((x) => x.text).join('\n'), edits: winner.edits })
|
|
505
|
-
: { applies: true, why: 'applies' };
|
|
506
|
-
if (!applied.applies) return yield* Effect.fail(`skill ${input.drafted.skill} changed since Draft, and the winner, candidate ${input.winner}, no longer applies to it: ${applied.why}`);
|
|
507
|
-
const newText = Result.getOrThrow(applyEdits(current.text, winner.edits));
|
|
508
|
-
const before = Date.now();
|
|
509
|
-
const attempt = yield* Effect.result(Effect.gen(function* () {
|
|
510
|
-
const installed = yield* files.install({ skill: input.drafted.skill, onSha: current.sha, newText, history: reply.history, example: reply.example, evalCase: { file: caseFile, json: JSON.stringify(evalCase, null, 1) } });
|
|
511
|
-
const syncListLine = yield* files.confirmSynced({ skill: input.drafted.skill, since: before, afterSha: installed.afterSha });
|
|
512
|
-
return { installed, syncListLine };
|
|
513
|
-
}));
|
|
514
|
-
if (Result.isFailure(attempt)) {
|
|
515
|
-
if (attempt.failure._tag === 'SkillChangedError' && tries < INSTALL_TRIES) continue;
|
|
516
|
-
return yield* Effect.fail(attempt.failure.reason);
|
|
517
|
-
}
|
|
518
|
-
const { installed, syncListLine } = attempt.success;
|
|
519
|
-
yield* deps.intake.recordInstalled(input.item, { item: input.item, run: input.run, rule: winner.summary, draftedOn: input.drafted.draftedOn, rebased, ...installed, syncListLine, at: new Date().toISOString() });
|
|
520
|
-
return { skill: installed.skill, wordsBefore: installed.wordsBefore, wordsAfter: installed.wordsAfter, files: installed.files, rebased, syncListLine };
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
|
|
524
|
-
/** An item's outcomes, oldest first, as the platform noted them. */
|
|
525
|
-
const outcomesOf = (item: string) => Effect.map(
|
|
526
|
-
Effect.orElseSucceed(deps.platform.tasks.taskNotes({ workflow: WORKFLOW, item }), () => []),
|
|
527
|
-
(notes): ReadonlyArray<NotedOutcome> => notes.filter((n) => n.kind === 'outcome').map((n) => ({ why: n.why, at: n.at })),
|
|
528
|
-
);
|
|
529
|
-
|
|
530
|
-
/** Whether an open item's retry time falls after `from` and by `to` (unix seconds): its waiting Pick is woken then, as nothing else wakes it. */
|
|
531
|
-
const retryFallsDue = (input: { readonly from: number; readonly to: number }) => Effect.orElseSucceed(Effect.gen(function* () {
|
|
532
|
-
for (const id of yield* deps.intake.open()) {
|
|
533
|
-
const newest = (yield* outcomesOf(id)).at(-1);
|
|
534
|
-
const at = newest === undefined ? null : retryAt(newest);
|
|
535
|
-
if (at !== null && at > input.from && at <= input.to) return true;
|
|
536
|
-
}
|
|
537
|
-
return false;
|
|
538
|
-
}), () => false);
|
|
539
|
-
|
|
540
|
-
const workflow = defineWorkflow<Outcome>({
|
|
541
|
-
phase: 'skills', at, item: 'feedback item', finishedWord: 'installed',
|
|
542
|
-
description: 'Turns each feedback item into a tested change to the synced skills.',
|
|
543
|
-
steps: () => [PICK, CALIBRATE, CLASSIFY, DRAFT, CHOOSE, AB, JUDGE, INSTALL],
|
|
544
|
-
picksQueueHead: true,
|
|
545
|
-
pending: () => Effect.orElseSucceed(Effect.map(deps.intake.open(), (open) => ({ lines: [{ label: 'feedback items to install', items: open }], waits: [] })), () => ({ lines: [], waits: [] })),
|
|
546
|
-
// An item that failed on Jev or the generative model also runs on the retry time that failure gives it (`retry.ts`).
|
|
547
|
-
taskInputs: () => Effect.orElseSucceed(Effect.gen(function* () {
|
|
548
|
-
const open = yield* deps.intake.open();
|
|
549
|
-
const now = deps.now();
|
|
550
|
-
const out = new Map<string, { readonly fingerprint: string }>();
|
|
551
|
-
for (const id of open) {
|
|
552
|
-
const retry = retryInput({ outcomes: yield* outcomesOf(id), now });
|
|
553
|
-
out.set(id, { fingerprint: shaOf(`${yield* deps.intake.text(id)}\n${deps.configFingerprint()}${retry === null ? '' : `\nretry at ${retry}`}`) });
|
|
554
|
-
}
|
|
555
|
-
return out as ReadonlyMap<string, { readonly fingerprint: string }>;
|
|
556
|
-
}), () => new Map()),
|
|
557
|
-
outcomes: (o) => (o.item === null ? [] : [{ subject: o.item, outcome: o.outcome, finished: o.finished }]),
|
|
558
|
-
graph: () => [
|
|
559
|
-
{ from: RUN_STARTS, to: PICK.name, when: 'each run' },
|
|
560
|
-
{ from: PICK.name, to: CALIBRATE.name, when: 'an item picked' },
|
|
561
|
-
{ from: CALIBRATE.name, to: CLASSIFY.name, when: 'the judge agrees with him at least as often as the Opus judge did' },
|
|
562
|
-
{ from: CALIBRATE.name, to: RUN_ENDS, when: 'the judge agrees with him less often: no model call is spent on the item' },
|
|
563
|
-
{ from: PICK.name, to: RUN_ENDS, when: 'the run is past its run limit' },
|
|
564
|
-
{ from: CLASSIFY.name, to: DRAFT.name, when: 'always' },
|
|
565
|
-
{ from: DRAFT.name, to: CHOOSE.name, when: 'a candidate applies, in the first round that has one' },
|
|
566
|
-
{ from: DRAFT.name, to: AB.name, when: 'a candidate applies, once the examples are chosen' },
|
|
567
|
-
{ from: DRAFT.name, to: DRAFT.name, when: 'no candidate applies, and a round is left: the next reads why' },
|
|
568
|
-
{ from: DRAFT.name, to: RUN_ENDS, when: 'no candidate applies in the last round' },
|
|
569
|
-
{ from: CHOOSE.name, to: AB.name, when: 'always' },
|
|
570
|
-
{ from: AB.name, to: JUDGE.name, when: 'always' },
|
|
571
|
-
{ from: JUDGE.name, to: INSTALL.name, when: 'a candidate wins' },
|
|
572
|
-
{ from: JUDGE.name, to: DRAFT.name, when: 'no candidate wins, and a round is left: the next reads why each reply failed' },
|
|
573
|
-
{ from: JUDGE.name, to: RUN_ENDS, when: 'no candidate wins in the last round' },
|
|
574
|
-
{ from: INSTALL.name, to: RUN_ENDS, when: 'always' },
|
|
575
|
-
{ from: A_STEP_FAILS, to: RUN_ENDS, when: 'a step fails' },
|
|
576
|
-
],
|
|
577
|
-
})(WORKFLOW, {
|
|
578
|
-
payload: { run: Schema.String },
|
|
579
|
-
idempotencyKey: ({ run }) => run,
|
|
580
|
-
success: Outcome,
|
|
581
|
-
error: Schema.String,
|
|
582
|
-
});
|
|
583
|
-
|
|
584
|
-
const layer = workflow.toLayer((payload) => Effect.gen(function* () {
|
|
585
|
-
const { run } = payload as { readonly run: string };
|
|
586
|
-
const picked = yield* PICK.run(pick(run));
|
|
587
|
-
if (Option.isNone(picked)) return { item: null, outcome: 'nothing picked', finished: false };
|
|
588
|
-
const item = picked.value;
|
|
589
|
-
// The judge is checked first: a judge that cannot be trusted would waste every model call after it.
|
|
590
|
-
const calibration = yield* CALIBRATE.run(calibrate());
|
|
591
|
-
if (!calibration.usable) return { item, outcome: `the judge is not calibrated: ${calibrationLine(calibration)}`, finished: false };
|
|
592
|
-
const classified = yield* CLASSIFY.run(classify(item));
|
|
593
|
-
let chosen: typeof Chosen.Type | null = null;
|
|
594
|
-
let previous: { readonly drafted: typeof Drafted.Type; readonly whyNoneWon: string } | null = null;
|
|
595
|
-
// The current text's replies and verdicts, once a round has written them: a later round drafted on the same text compares against these.
|
|
596
|
-
let currentText: { readonly sha: string; readonly replies: string; readonly verdicts: string } | null = null;
|
|
597
|
-
let outcome = '';
|
|
598
|
-
for (let round = 1; round <= DRAFT_ROUNDS; round++) {
|
|
599
|
-
// The first round's steps keep their plain names, so a run started before rounds existed resumes from its records.
|
|
600
|
-
const call = round === 1 ? undefined : { call: round };
|
|
601
|
-
const drafted: typeof Drafted.Type = yield* DRAFT.run(draft({ item, run, classified, round, previous }), call);
|
|
602
|
-
if (!drafted.candidates.some((c) => c.applies)) {
|
|
603
|
-
const why = drafted.candidates.map((c) => c.why).join('; ');
|
|
604
|
-
outcome = `no candidate applies: ${why}`;
|
|
605
|
-
previous = { drafted, whyNoneWon: `none applied: ${why}` };
|
|
606
|
-
continue;
|
|
607
|
-
}
|
|
608
|
-
chosen = chosen ?? (yield* CHOOSE.run(choose(classified)));
|
|
609
|
-
// Replies to a text that has changed since (another machine's edit pulled between rounds) are not this text's: written again.
|
|
610
|
-
const reuse = currentText !== null && currentText.sha === drafted.draftedOn ? currentText : null;
|
|
611
|
-
const replies: typeof Replies.Type = yield* AB.run(ab({ run, drafted, chosen, item, round, currentTextReplies: reuse === null ? null : reuse.replies }), call);
|
|
612
|
-
const ranked: typeof Ranked.Type = yield* JUDGE.run(judge({ run, replies, round, currentTextVerdicts: reuse === null ? null : reuse.verdicts }), call);
|
|
613
|
-
if (ranked.winner !== null) {
|
|
614
|
-
const installed = yield* INSTALL.run(install({ item, run, drafted, winner: ranked.winner }));
|
|
615
|
-
return { item, outcome: `installed in ${installed.skill} (${installed.wordsBefore} to ${installed.wordsAfter} words)${round === 1 ? '' : `, from draft ${round}`}`, finished: true };
|
|
616
|
-
}
|
|
617
|
-
outcome = `no candidate wins: ${ranked.why}`;
|
|
618
|
-
previous = { drafted, whyNoneWon: ranked.why };
|
|
619
|
-
currentText = { sha: drafted.draftedOn, replies: replies.file, verdicts: ranked.file };
|
|
620
|
-
}
|
|
621
|
-
return { item, outcome: `after ${DRAFT_ROUNDS} drafts, ${outcome}`, finished: false };
|
|
622
|
-
}));
|
|
623
|
-
|
|
624
|
-
return { workflow, layer, retryFallsDue, steps: { PICK, CLASSIFY, DRAFT, CHOOSE, CALIBRATE, AB, JUDGE, INSTALL } };
|
|
625
|
-
};
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
/** One reply's verdict, by its case kind's judge, as `judged.json` keeps it. */
|
|
629
|
-
type Judged = { readonly caseId: string; readonly version: number; readonly sample: number; readonly pass: boolean; readonly score: number }
|
|
630
|
-
& ({ readonly judge: 'opus'; readonly verdict: ActionVerdict } | { readonly judge: 'jev'; readonly answers: unknown });
|
|
631
|
-
|
|
632
|
-
/** Why each failing reply failed: the Opus judge's sentence, or the reply criteria Jev failed it on. Pure. */
|
|
633
|
-
export const failureReasons = (judged: ReadonlyArray<
|
|
634
|
-
{ readonly caseId: string; readonly version: number; readonly sample: number; readonly pass: boolean }
|
|
635
|
-
& ({ readonly judge: 'opus'; readonly verdict: ActionVerdict } | { readonly judge: 'jev'; readonly answers: unknown })
|
|
636
|
-
>): ReadonlyArray<string> => judged.filter((j) => !j.pass).map((j) => {
|
|
637
|
-
const failed = j.judge === 'opus'
|
|
638
|
-
? j.verdict.why
|
|
639
|
-
: `failed ${Object.entries(REPLY_CRITERIA).filter(([k, c]) => { const yes = (j.answers as Record<string, number>)[k] ?? 0; return (c.passesWhen === 'yes' ? yes : 1 - yes) < 0.5; }).map(([k]) => k).join(', ')}`;
|
|
640
|
-
return `${j.caseId} ${j.version === 0 ? 'current' : `candidate ${j.version}`} sample ${j.sample}: ${failed}`;
|
|
641
|
-
});
|
|
642
|
-
|
|
643
|
-
/** Each version's passes, the cases it loses that the current text wins, and the winner. Pure. */
|
|
644
|
-
export const rank = (judged: ReadonlyArray<{ readonly caseId: string; readonly version: number; readonly pass: boolean; readonly score: number }>) => {
|
|
645
|
-
const versions = [...new Set(judged.map((j) => j.version))].sort((a, b) => a - b);
|
|
646
|
-
const caseIds = [...new Set(judged.map((j) => j.caseId))];
|
|
647
|
-
const passesCase = (version: number, caseId: string) => {
|
|
648
|
-
const samples = judged.filter((j) => j.version === version && j.caseId === caseId);
|
|
649
|
-
return samples.filter((s) => s.pass).length * 2 > samples.length;
|
|
650
|
-
};
|
|
651
|
-
const rows = versions.map((v) => ({
|
|
652
|
-
version: v === 0 ? 'current' : `candidate ${v}`,
|
|
653
|
-
passes: caseIds.filter((c) => passesCase(v, c)).length,
|
|
654
|
-
of: caseIds.length,
|
|
655
|
-
score: judged.filter((j) => j.version === v).reduce((s, j) => s + j.score, 0),
|
|
656
|
-
losesTo: v === 0 ? [] : caseIds.filter((c) => passesCase(0, c) && !passesCase(v, c)),
|
|
657
|
-
}));
|
|
658
|
-
const ownCase = caseIds.find((c) => c.startsWith('this item'));
|
|
659
|
-
const eligible = versions.filter((v) => v !== 0 && rows[versions.indexOf(v)]!.losesTo.length === 0 && (ownCase === undefined || passesCase(v, ownCase)));
|
|
660
|
-
const best = eligible.sort((a, b) => rows[versions.indexOf(b)]!.passes - rows[versions.indexOf(a)]!.passes || rows[versions.indexOf(b)]!.score - rows[versions.indexOf(a)]!.score)[0];
|
|
661
|
-
const why = best === undefined
|
|
662
|
-
? `no candidate passes the item's own case without failing a case the current text passes (${rows.map((r) => `${r.version}: ${r.passes}/${r.of}`).join(', ')})`
|
|
663
|
-
: `candidate ${best} passes ${rows[versions.indexOf(best)]!.passes} of ${caseIds.length} cases, the current text ${rows[0]!.passes}`;
|
|
664
|
-
return { versions: rows, winner: best ?? null, why };
|
|
665
|
-
};
|