@jive-sh/skill-sync 0.9.0 → 0.10.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 -45
- package/README.md +0 -208
- package/bin/package.json +0 -1
- package/bin/skill-sync +0 -34
- package/bin/skill-sync-daemon +0 -34
- package/dist/daemons/skill-sync-daemon.js +0 -640
- 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 -63
- package/dist/internal/skill-refinement/jev/impl.js.map +0 -1
- package/dist/internal/skill-refinement/jev/interface.js +0 -6
- 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 -67
- package/dist/internal/skill-refinement/platform.js.map +0 -1
- package/dist/internal/skill-refinement/service.js +0 -261
- 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 -597
- package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +0 -1
- package/dist/internal/skill-refinement/writer/impl.js +0 -74
- package/dist/internal/skill-refinement/writer/impl.js.map +0 -1
- package/dist/internal/skill-refinement/writer/interface.js +0 -6
- 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/postinstall.cjs +0 -663
- package/src/daemons/skill-sync-daemon.ts +0 -645
- 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 -76
- package/src/internal/skill-refinement/jev/interface.ts +0 -56
- package/src/internal/skill-refinement/paths.ts +0 -87
- package/src/internal/skill-refinement/platform.ts +0 -71
- package/src/internal/skill-refinement/service.ts +0 -307
- 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 -671
- package/src/internal/skill-refinement/writer/impl.ts +0 -86
- package/src/internal/skill-refinement/writer/interface.ts +0 -34
- package/src/internal/sync.ts +0 -216
- package/src/internal/wire.ts +0 -439
|
@@ -1,307 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* THE SKILL REFINEMENT RUNNER: hosts the workflow engine inside the skill-sync daemon and keeps the workflow's runs going.
|
|
3
|
-
* Each turn it reads the intake (the workflow's list of work) and starts the runs the workflow's run limit keeps above those
|
|
4
|
-
* going (`planRunStarts`). A turn runs when an item lands in the intake, when a run ends, and otherwise every minute as the
|
|
5
|
-
* fallback. The daemon starts it (`startSkillRefinement`), reports what the platform's dashboard shows (`pageData`) and
|
|
6
|
-
* passes on the dashboard's limit changes (`setLimit`).
|
|
7
|
-
*
|
|
8
|
-
* Configuration, read once at the start: `TYPESAFE_API_KEY` (or the skill folder's `typesafe-api-key` file) for Jev, and
|
|
9
|
-
* `SKILL_REFINEMENT_CLAUDE_CONFIG_DIR`, the Claude Code config folder whose account the generative calls run on (by
|
|
10
|
-
* default the account folder holding the copy the runner works from, `locateSkillCopy`). Nothing here names a machine.
|
|
11
|
-
*/
|
|
12
|
-
import { SqliteClient } from '@effect/sql-sqlite-bun';
|
|
13
|
-
import {
|
|
14
|
-
claimsCounting,
|
|
15
|
-
describeFailure, KEEP_RUNNING_EVERY_SECONDS, newRunId, oneTurnAtATime, planRunStarts, runsNow, SET_WORKFLOW_BUDGET_SQL, SET_WORKFLOW_RUNS_SQL,
|
|
16
|
-
START_LIMIT_SECONDS, TURN_LIMIT_MS, WORKFLOW_BUDGET_SQL,
|
|
17
|
-
} from '@jive-sh/workflow-platform';
|
|
18
|
-
import { Database } from 'bun:sqlite';
|
|
19
|
-
import { Crypto, Duration, Effect, Layer, ManagedRuntime, Option, pipe } from 'effect';
|
|
20
|
-
import { ClusterWorkflowEngine, RunnerAddress, SingleRunner } from 'effect/cluster';
|
|
21
|
-
import fs from 'node:fs';
|
|
22
|
-
import os from 'node:os';
|
|
23
|
-
import path from 'node:path';
|
|
24
|
-
import { judgeVersion } from './evals/cases';
|
|
25
|
-
import { makeIntake } from './feedback/intake';
|
|
26
|
-
import { JevLive } from './jev/impl';
|
|
27
|
-
import { engineDatabase, installedFolder, intakeFolder, locateSkillCopy, machineIntakeFolders, platformDatabase, runFolder, type WorkflowFolders } from './paths';
|
|
28
|
-
import OPUS_JUDGE_ORIGINAL from './evals/opus-judge-original.json';
|
|
29
|
-
import OPUS_ACTION_JUDGE_ORIGINAL from './evals/opus-action-judge-original.json';
|
|
30
|
-
import { skillRefinementPlatform } from './platform';
|
|
31
|
-
import { SkillFiles, SkillFilesLive, skillsTextSha, type SyncedSkills } from './skills/skill-text';
|
|
32
|
-
import type { Jev } from './jev/interface';
|
|
33
|
-
import type { Writer } from './writer/interface';
|
|
34
|
-
import { defineSkillRefinement, draftVersion, WORKFLOW } from './workflow/skill-refinement';
|
|
35
|
-
import { WriterLive } from './writer/impl';
|
|
36
|
-
import type { LimitChange, RefinementPageData } from '../wire';
|
|
37
|
-
|
|
38
|
-
/** Bun's WebCrypto, as the cluster's message storage needs it. */
|
|
39
|
-
const CryptoLive = Layer.succeed(Crypto.Crypto, Crypto.make({
|
|
40
|
-
randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)),
|
|
41
|
-
digest: (algorithm, data) => Effect.promise(async () => new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, new Uint8Array(data)))),
|
|
42
|
-
}));
|
|
43
|
-
|
|
44
|
-
export interface ServiceConfig {
|
|
45
|
-
readonly folders: WorkflowFolders;
|
|
46
|
-
/** Jev's API key, read when used; empty while none is set, so its steps fail with that reason. */
|
|
47
|
-
readonly typesafeApiKey: () => string;
|
|
48
|
-
readonly jevModel: string;
|
|
49
|
-
readonly claudeConfigDir: string;
|
|
50
|
-
readonly writerModel: string;
|
|
51
|
-
/** The Opus judge's grades of the original replies, the bar Jev is calibrated against. */
|
|
52
|
-
readonly opusJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
|
|
53
|
-
/** The evals' original action-judge prompt's grades of the action originals, the bar the action judge is held to. */
|
|
54
|
-
readonly opusActionJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
|
|
55
|
-
/** Every intake the items are read from (`machineIntakeFolders`). */
|
|
56
|
-
readonly intakes: ReadonlyArray<string>;
|
|
57
|
-
/** The time now, unix seconds, which decides when a failed item runs again (`retry.ts`); a test gives its own clock. */
|
|
58
|
-
readonly now?: () => number;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* EACH WORKFLOW STARTS AT ONE RUN AND ONE AGENT (`spawn-subthread` section 2, step 3): set once, never changed here; the
|
|
63
|
-
* owner changes them in the `workflow_budgets` table.
|
|
64
|
-
*/
|
|
65
|
-
const ensureLimits = (folders: WorkflowFolders) => {
|
|
66
|
-
const db = new Database(platformDatabase(folders), { create: true });
|
|
67
|
-
try {
|
|
68
|
-
db.run('CREATE TABLE IF NOT EXISTS workflow_budgets (workflow TEXT PRIMARY KEY, budget INTEGER NOT NULL, runs INTEGER, changed_at REAL NOT NULL)');
|
|
69
|
-
if (db.query(WORKFLOW_BUDGET_SQL).get(WORKFLOW) === null) {
|
|
70
|
-
db.query(SET_WORKFLOW_BUDGET_SQL).run(WORKFLOW, 1, Date.now() / 1000);
|
|
71
|
-
db.query(SET_WORKFLOW_RUNS_SQL).run(WORKFLOW, 1, Date.now() / 1000);
|
|
72
|
-
}
|
|
73
|
-
} finally {
|
|
74
|
-
db.close();
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
/** The workflow, its engine and its modules, on one machine's folders; a test gives fake modules. */
|
|
79
|
-
export const makeService = (config: ServiceConfig, modules: Layer.Layer<Jev | Writer | SkillFiles>) => {
|
|
80
|
-
const { folders } = config;
|
|
81
|
-
fs.mkdirSync(intakeFolder(folders), { recursive: true });
|
|
82
|
-
ensureLimits(folders);
|
|
83
|
-
const platform = skillRefinementPlatform(folders);
|
|
84
|
-
const intake = makeIntake({ intake: intakeFolder(folders), intakes: config.intakes, installed: installedFolder(folders) });
|
|
85
|
-
// Everything a run reads beyond the item: an item that ended without an install runs again once any of it changes.
|
|
86
|
-
// A key put in place queues the items its absence stopped; a change to Draft or the judge queues every item that
|
|
87
|
-
// ended under the old one; an edit to a skill (an install, another machine's edit pulled) queues those that would draft on it.
|
|
88
|
-
const now = config.now ?? (() => Date.now() / 1000);
|
|
89
|
-
const configFingerprint = () => JSON.stringify({
|
|
90
|
-
judge: judgeVersion(), draft: draftVersion(), skills: skillsTextSha(folders.skills),
|
|
91
|
-
jev: config.jevModel, jevKeySet: config.typesafeApiKey().length > 0, writer: config.writerModel, account: config.claudeConfigDir,
|
|
92
|
-
});
|
|
93
|
-
const maintenance = defineSkillRefinement({ platform, intake, folders, opusJudgeGrades: config.opusJudgeGrades, opusActionJudgeGrades: config.opusActionJudgeGrades, configFingerprint, now, models: { jev: config.jevModel, writer: config.writerModel } });
|
|
94
|
-
const layer = pipe(
|
|
95
|
-
// The platform's own workflows (Retention) run in the same engine as this one.
|
|
96
|
-
Layer.mergeAll(maintenance.layer as Layer.Layer<never>, platform.system.layer as Layer.Layer<never>),
|
|
97
|
-
Layer.provideMerge(ClusterWorkflowEngine.layer),
|
|
98
|
-
Layer.provideMerge(SingleRunner.layer({
|
|
99
|
-
runnerStorage: 'sql',
|
|
100
|
-
shardingConfig: { runnerAddress: Option.some(RunnerAddress.make('skill-refinement', process.pid)), entityTerminationTimeout: Duration.minutes(10) },
|
|
101
|
-
})),
|
|
102
|
-
Layer.provideMerge(SqliteClient.layer({ filename: engineDatabase(folders), busyTimeout: Duration.seconds(1) })),
|
|
103
|
-
Layer.provideMerge(CryptoLive),
|
|
104
|
-
Layer.provideMerge(modules),
|
|
105
|
-
);
|
|
106
|
-
const runtime = ManagedRuntime.make(layer);
|
|
107
|
-
|
|
108
|
-
/** One turn: the list read into the task queue, then the runs the limits keep, started and left to the engine. */
|
|
109
|
-
const turn = oneTurnAtATime(async (stillCurrent) => {
|
|
110
|
-
const declared = platform.steps.declaredWorkflows();
|
|
111
|
-
for (const d of declared) {
|
|
112
|
-
if (d.pending === undefined) continue;
|
|
113
|
-
const work = await Effect.runPromise(d.pending());
|
|
114
|
-
await Effect.runPromise(platform.tasks.recordListing({ workflow: d.name, work, everyItem: false }));
|
|
115
|
-
}
|
|
116
|
-
const limits = await Effect.runPromise(platform.storage.budgets.limitsOf(WORKFLOW));
|
|
117
|
-
const going = await Effect.runPromise(platform.storage.engine.runningRuns(WORKFLOW));
|
|
118
|
-
const noWork = await Effect.runPromise(platform.steps.whyNoRunCanTakeWork(WORKFLOW));
|
|
119
|
-
const plans = planRunStarts({
|
|
120
|
-
declared,
|
|
121
|
-
limitsOf: () => limits ?? { agents: 0, runs: null },
|
|
122
|
-
runningRuns: () => going,
|
|
123
|
-
noWork: () => noWork,
|
|
124
|
-
});
|
|
125
|
-
for (const p of plans) {
|
|
126
|
-
for (let i = 0; i < p.start; i++) {
|
|
127
|
-
if (!stillCurrent()) return;
|
|
128
|
-
const run = newRunId();
|
|
129
|
-
try {
|
|
130
|
-
await runtime.runPromise(Effect.timeout(Effect.asVoid(p.declaration.start(run)), `${START_LIMIT_SECONDS} seconds`));
|
|
131
|
-
console.log(`[keep running] ${p.declaration.name}: started run ${run}`);
|
|
132
|
-
} catch (e) {
|
|
133
|
-
console.error(`[keep running] ${p.declaration.name}: run ${run} did not start: ${describeFailure(e)}`);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}, TURN_LIMIT_MS);
|
|
138
|
-
const kick = () => { void turn().catch((e: unknown) => console.error(`[keep running] ${describeFailure(e)}`)); };
|
|
139
|
-
platform.steps.onRunEnded(kick);
|
|
140
|
-
// A retry time passing (`retry.ts`) changes an item's inputs with no note, listing or edit to announce it: the waiting
|
|
141
|
-
// Pick is woken for it. The first check covers every time already passed, so a restart picks up what fell due while down.
|
|
142
|
-
let retriesCheckedTo = 0;
|
|
143
|
-
const wakeDueRetries = async () => {
|
|
144
|
-
const to = now();
|
|
145
|
-
const due = await runtime.runPromise(maintenance.retryFallsDue({ from: retriesCheckedTo, to }));
|
|
146
|
-
retriesCheckedTo = to;
|
|
147
|
-
if (due) platform.wakes.wakePicksOf(WORKFLOW, "a failed item's retry time passed");
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
return { platform, intake, runtime, turn, kick, wakeDueRetries };
|
|
151
|
-
};
|
|
152
|
-
|
|
153
|
-
/** What the live modules need beyond the service's configuration: the `claude` CLI, and skill-sync's synced list. */
|
|
154
|
-
export interface LiveInputs {
|
|
155
|
-
readonly claudeCommand: string;
|
|
156
|
-
readonly syncedSkills: SyncedSkills;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** The live modules the workflow's steps call: Jev, the generative model and the synced skills. */
|
|
160
|
-
export const liveModules = (config: ServiceConfig, live: LiveInputs): Layer.Layer<Jev | Writer | SkillFiles> => Layer.mergeAll(
|
|
161
|
-
JevLive({ apiKey: config.typesafeApiKey, model: config.jevModel }),
|
|
162
|
-
WriterLive({ claudeCommand: live.claudeCommand, claudeConfigDir: config.claudeConfigDir, model: config.writerModel, scratch: runFolder(config.folders, 'writer-scratch') }),
|
|
163
|
-
SkillFilesLive({ root: config.folders.skills, syncedSkills: live.syncedSkills }),
|
|
164
|
-
);
|
|
165
|
-
|
|
166
|
-
/** The window of each workflow's figures, as the platform's dashboard states it. */
|
|
167
|
-
const FIGURES_HOURS = 24;
|
|
168
|
-
/** A runner whose heartbeat is older than this is gone, whatever its process does now. */
|
|
169
|
-
const RUNNER_HEARTBEAT_STALE_MS = 60_000;
|
|
170
|
-
|
|
171
|
-
/** The running workflow, as the daemon uses it. */
|
|
172
|
-
export interface SkillRefinementRunner {
|
|
173
|
-
/** The dashboard's data, all of it read at the call. */
|
|
174
|
-
readonly pageData: () => Promise<RefinementPageData>;
|
|
175
|
-
/** Sets one limit of the workflow and has its runs act on it at once. A whole number of 0 or more; none, for runs only, is its default. */
|
|
176
|
-
readonly setLimit: (r: LimitChange) => Promise<void>;
|
|
177
|
-
/** Hands one feedback item to the workflow, in this machine's copy of the skill; gives its id. */
|
|
178
|
-
readonly addFeedback: (r: { readonly slug: string; readonly text: string }) => Promise<string>;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** Why this machine runs no workflow, in a line for the daemon's log and the dashboard. */
|
|
182
|
-
export type NotRunning = { readonly notRunning: string };
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* Another live process running this workflow on the same engine database: the runner a machine had before the daemon
|
|
186
|
-
* took the work over (`skill-refinement.service`), or a copy started by hand. Read from the engine's own runner
|
|
187
|
-
* registrations, each named `<host>:<pid>` and heartbeating while it lives.
|
|
188
|
-
*/
|
|
189
|
-
export const otherLiveRunner = (folders: WorkflowFolders, now: number): string | null => {
|
|
190
|
-
const file = engineDatabase(folders);
|
|
191
|
-
if (!fs.existsSync(file)) return null;
|
|
192
|
-
const db = new Database(file, { readonly: true });
|
|
193
|
-
try {
|
|
194
|
-
if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'cluster_runners'`).get() === null) return null;
|
|
195
|
-
const rows = db.query('SELECT address, last_heartbeat FROM cluster_runners').all() as ReadonlyArray<{ address: string; last_heartbeat: string }>;
|
|
196
|
-
for (const row of rows) {
|
|
197
|
-
const pid = Number(row.address.split(':').pop());
|
|
198
|
-
const beat = Date.parse(`${row.last_heartbeat.replace(' ', 'T')}Z`);
|
|
199
|
-
if (!Number.isInteger(pid) || pid === process.pid || Number.isNaN(beat) || now - beat > RUNNER_HEARTBEAT_STALE_MS) continue;
|
|
200
|
-
try {
|
|
201
|
-
process.kill(pid, 0);
|
|
202
|
-
return `process ${pid} runs it (heartbeat ${new Date(beat).toISOString()})`;
|
|
203
|
-
} catch {
|
|
204
|
-
// Gone: its row is left from before.
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
return null;
|
|
208
|
-
} finally {
|
|
209
|
-
db.close();
|
|
210
|
-
}
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Starts the workflow on this machine's copy of the skill, once no other process runs it. Waits, checking every minute,
|
|
215
|
-
* while one does, so the runner a machine had before hands over by stopping. Gives the runner, or why there is none.
|
|
216
|
-
*/
|
|
217
|
-
export const startSkillRefinement = async (input: {
|
|
218
|
-
readonly home: string;
|
|
219
|
-
readonly claudeCommand: string | undefined;
|
|
220
|
-
readonly syncedSkills: SyncedSkills;
|
|
221
|
-
/** Called once the runner is up, and again with why whenever it is waiting or cannot run. */
|
|
222
|
-
readonly onState: (state: SkillRefinementRunner | NotRunning) => void;
|
|
223
|
-
}): Promise<void> => {
|
|
224
|
-
const copy = locateSkillCopy({ home: input.home, claudeConfigDir: process.env["SKILL_REFINEMENT_CLAUDE_CONFIG_DIR"] });
|
|
225
|
-
if (copy === null) return input.onState({ notRunning: 'this machine has no copy of the autonomous-skill-refinement skill' });
|
|
226
|
-
if (input.claudeCommand === undefined) return input.onState({ notRunning: 'no `claude` CLI was found on this machine for the drafting and A/B steps' });
|
|
227
|
-
let waitingFor = '';
|
|
228
|
-
for (;;) {
|
|
229
|
-
const other = otherLiveRunner(copy.folders, Date.now());
|
|
230
|
-
if (other === null) break;
|
|
231
|
-
if (other !== waitingFor) input.onState({ notRunning: `waiting to take over: ${other}` });
|
|
232
|
-
waitingFor = other;
|
|
233
|
-
await Bun.sleep(60_000);
|
|
234
|
-
}
|
|
235
|
-
const config: ServiceConfig = {
|
|
236
|
-
folders: copy.folders,
|
|
237
|
-
typesafeApiKey: () => process.env["TYPESAFE_API_KEY"] ?? (fs.existsSync(copy.jevKeyFile) ? fs.readFileSync(copy.jevKeyFile, 'utf8').trim() : ''),
|
|
238
|
-
jevModel: 'jev-latest',
|
|
239
|
-
claudeConfigDir: process.env["SKILL_REFINEMENT_CLAUDE_CONFIG_DIR"] ?? copy.accountFolder,
|
|
240
|
-
writerModel: 'claude-opus-5-5',
|
|
241
|
-
opusJudgeGrades: OPUS_JUDGE_ORIGINAL.grades,
|
|
242
|
-
opusActionJudgeGrades: OPUS_ACTION_JUDGE_ORIGINAL.grades,
|
|
243
|
-
intakes: machineIntakeFolders({ home: input.home, own: copy.folders }),
|
|
244
|
-
};
|
|
245
|
-
const service = makeService(config, liveModules(config, { claudeCommand: input.claudeCommand, syncedSkills: input.syncedSkills }));
|
|
246
|
-
console.log(`[skill refinement] working from ${copy.skillFolder}; Jev key ${config.typesafeApiKey().length > 0 ? 'set' : 'NOT set: Classify fails until it is'}; generative calls on ${config.claudeConfigDir} with ${input.claudeCommand}`);
|
|
247
|
-
// The engine starts with the runtime; resumed runs continue from their records.
|
|
248
|
-
await service.runtime.runPromise(Effect.void);
|
|
249
|
-
for (const folder of config.intakes) fs.watch(folder, () => service.kick());
|
|
250
|
-
// The key's arrival changes every task's inputs (`configFingerprint`), which no note or listing announces: the waiting Pick is woken to read them.
|
|
251
|
-
fs.watch(copy.skillFolder, (_, file) => { if (file === path.basename(copy.jevKeyFile)) service.platform.wakes.wakePicksOf(WORKFLOW, 'the Jev key was set'); });
|
|
252
|
-
// Likewise a skill's text (`configFingerprint`): one pulled from another machine arrives with no run or item to wake the Pick.
|
|
253
|
-
for (const skill of fs.readdirSync(copy.folders.skills).filter((d) => fs.existsSync(path.join(copy.folders.skills, d, 'SKILL.md')))) {
|
|
254
|
-
fs.watch(path.join(copy.folders.skills, skill), (_, file) => { if (file === 'SKILL.md') service.platform.wakes.wakePicksOf(WORKFLOW, `skill ${skill} changed`); });
|
|
255
|
-
}
|
|
256
|
-
const keepRunning = () => {
|
|
257
|
-
void service.wakeDueRetries().catch((e: unknown) => console.error(`[skill refinement] could not check for retries due: ${describeFailure(e)}`));
|
|
258
|
-
service.kick();
|
|
259
|
-
};
|
|
260
|
-
setInterval(keepRunning, KEEP_RUNNING_EVERY_SECONDS * 1000);
|
|
261
|
-
keepRunning();
|
|
262
|
-
// The platform's own workflows, each on its own schedule: Retention prunes step records past the days they are kept.
|
|
263
|
-
for (const w of service.platform.system.workflows) {
|
|
264
|
-
let turn = 0;
|
|
265
|
-
const runIt = () => { turn += 1; void service.runtime.runPromise(w.start(turn)).catch((e: unknown) => console.error(`[skill refinement] ${w.name} did not start: ${describeFailure(e)}`)); };
|
|
266
|
-
setTimeout(() => { runIt(); setInterval(runIt, w.everySeconds * 1000); }, w.firstAfterSeconds * 1000);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
const { platform } = service;
|
|
270
|
-
// Each queue counted when it may have changed, for the dashboard's queues over time; only the process running the workflow records them.
|
|
271
|
-
platform.queueCounts.record((count) => service.runtime.runPromise(count));
|
|
272
|
-
input.onState({
|
|
273
|
-
pageData: async () => {
|
|
274
|
-
const now = Date.now() / 1000;
|
|
275
|
-
const declared = platform.steps.declaredWorkflows();
|
|
276
|
-
const unfinished = await Effect.runPromise(platform.storage.engine.unfinishedRuns());
|
|
277
|
-
const newest = await Effect.runPromise(platform.storage.stepRecords.newestStepRecords(unfinished.map((u) => u.run)));
|
|
278
|
-
const figures: Record<string, object> = {};
|
|
279
|
-
for (const d of declared) {
|
|
280
|
-
const read = await Effect.runPromise(platform.figures({ workflow: d.name, now, hours: FIGURES_HOURS }));
|
|
281
|
-
if (read !== null) figures[d.name] = read;
|
|
282
|
-
}
|
|
283
|
-
return {
|
|
284
|
-
view: await Effect.runPromise(platform.view({ now, top: WORKFLOW })),
|
|
285
|
-
runsNow: runsNow({ declared, unfinished, newest, claims: claimsCounting(await Effect.runPromise(platform.storage.claims.openAgentClaims()), new Set(unfinished.map((u) => u.run))) }),
|
|
286
|
-
cpu: { limit: os.cpus().length, use: null },
|
|
287
|
-
figures,
|
|
288
|
-
};
|
|
289
|
-
},
|
|
290
|
-
setLimit: async ({ workflow, limit, value }) => {
|
|
291
|
-
if (!platform.steps.declaredWorkflows().some((d) => d.name === workflow)) throw new Error(`no workflow ${workflow} runs here`);
|
|
292
|
-
if (value !== null && (!Number.isInteger(value) || value < 0)) throw new Error(`a limit is a whole number of 0 or more, not ${value}`);
|
|
293
|
-
if (value === null && limit === 'agents') throw new Error('the agents\' limit needs a number');
|
|
294
|
-
const db = new Database(platformDatabase(copy.folders));
|
|
295
|
-
try {
|
|
296
|
-
db.query(limit === 'runs' ? SET_WORKFLOW_RUNS_SQL : SET_WORKFLOW_BUDGET_SQL).run(workflow, value, Date.now() / 1000);
|
|
297
|
-
} finally {
|
|
298
|
-
db.close();
|
|
299
|
-
}
|
|
300
|
-
// A run past a lower limit stands down at its next agent step; a higher one starts more at once.
|
|
301
|
-
platform.wakes.runPlanChanged({ workflow, source: `its ${limit === 'runs' ? 'run' : 'agents\''} limit set from the dashboard` });
|
|
302
|
-
service.kick();
|
|
303
|
-
console.log(`[skill refinement] ${workflow}: ${limit} limit set to ${String(value)} from the dashboard`);
|
|
304
|
-
},
|
|
305
|
-
addFeedback: ({ slug, text }) => Effect.runPromise(service.intake.add({ arrived: new Date(), slug, text })),
|
|
306
|
-
});
|
|
307
|
-
};
|
|
@@ -1,290 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* THE SYNCED SKILLS AS THIS WORKFLOW READS AND CHANGES THEM: each skill's text and its sections, its example names, and
|
|
3
|
-
* the one write that installs a change. skill-sync copies whatever is installed here to every machine; this module only
|
|
4
|
-
* reads skill-sync's synced list (`SyncedSkills`), before an install and after it.
|
|
5
|
-
*/
|
|
6
|
-
import { Context, Data, Duration, Effect, Layer, Result } from 'effect';
|
|
7
|
-
import type { ListedSkill } from '../../wire';
|
|
8
|
-
import fs from 'node:fs';
|
|
9
|
-
import path from 'node:path';
|
|
10
|
-
|
|
11
|
-
/** One `##` or `###` section of a skill, by the label a classifier chooses it by. */
|
|
12
|
-
export interface SkillSection {
|
|
13
|
-
readonly skill: string;
|
|
14
|
-
/** `skill § heading › subheading`, unique across the skills. */
|
|
15
|
-
readonly label: string;
|
|
16
|
-
readonly text: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** A skill's whole text, and the hash it had when read, so an install never overwrites a change made since. */
|
|
20
|
-
export interface SkillText {
|
|
21
|
-
readonly skill: string;
|
|
22
|
-
readonly text: string;
|
|
23
|
-
readonly sha: string;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/** One exact replacement in a skill's text: `find` must occur in it exactly once. */
|
|
27
|
-
export interface SkillEdit {
|
|
28
|
-
readonly find: string;
|
|
29
|
-
readonly replace: string;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** What an install wrote, for its record. */
|
|
33
|
-
export interface Installed {
|
|
34
|
-
readonly skill: string;
|
|
35
|
-
readonly beforeSha: string;
|
|
36
|
-
readonly afterSha: string;
|
|
37
|
-
readonly wordsBefore: number;
|
|
38
|
-
readonly wordsAfter: number;
|
|
39
|
-
readonly files: ReadonlyArray<string>;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export class SkillFilesError extends Data.TaggedError('SkillFilesError')<{ readonly reason: string }> {}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* The skill's text is no longer the text a change was built on: an edit made here, or pulled from another machine, landed
|
|
46
|
-
* while the change was being written, or replaced it afterwards. The caller builds the change again on the new text.
|
|
47
|
-
*/
|
|
48
|
-
export class SkillChangedError extends Data.TaggedError('SkillChangedError')<{ readonly skill: string; readonly reason: string }> {}
|
|
49
|
-
|
|
50
|
-
export const shaOf = (text: string): string => new Bun.CryptoHasher('sha256').update(text).digest('hex');
|
|
51
|
-
const words = (text: string): number => text.split(/\s+/).filter(Boolean).length;
|
|
52
|
-
|
|
53
|
-
/** A skill's sections: each `##` heading, and each `###` under it as `heading › subheading`. Pure. */
|
|
54
|
-
export const sectionsOf = (skill: string, text: string): ReadonlyArray<SkillSection> => {
|
|
55
|
-
const out: Array<{ label: string; lines: string[] }> = [];
|
|
56
|
-
let h2: string | null = null;
|
|
57
|
-
for (const line of text.split('\n')) {
|
|
58
|
-
const two = /^## (.+)$/.exec(line);
|
|
59
|
-
const three = /^### (.+)$/.exec(line);
|
|
60
|
-
if (two !== null) { h2 = two[1]!.trim(); out.push({ label: `${skill} § ${h2}`, lines: [] }); continue; }
|
|
61
|
-
if (three !== null) { out.push({ label: `${skill} § ${h2 ?? '(top)'} › ${three[1]!.trim()}`, lines: [] }); continue; }
|
|
62
|
-
out[out.length - 1]?.lines.push(line);
|
|
63
|
-
}
|
|
64
|
-
return out.map((s) => ({ skill, label: s.label, text: s.lines.join('\n').trim() })).filter((s) => s.text.length > 0);
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* The sections a section points to in another skill for its rules: each `skill` section N, or `skill` § N, it names, as
|
|
69
|
-
* that skill's section N and the subsections under it. senior-swe § 1 › Communicating precisely opens "Reply shape, length,
|
|
70
|
-
* links and **Blocked on you**: `agentic-collaboration` section 2", and Classify placed three Blocked on you items there
|
|
71
|
-
* (2026-11-20), one of which installed its rule on that pointer line, apart from the rules it belongs with. Pure.
|
|
72
|
-
*/
|
|
73
|
-
export const pointedSections = (section: SkillSection, sections: ReadonlyArray<SkillSection>): ReadonlyArray<SkillSection> => {
|
|
74
|
-
const prefixes = [...section.text.matchAll(/`([a-z0-9-]+)`(?:'s)? (?:section|§) ?(\d+[a-z]?)\b/g)]
|
|
75
|
-
.filter((pointer) => pointer[1] !== section.skill)
|
|
76
|
-
.map((pointer) => `${pointer[1]} § ${pointer[2]}.`);
|
|
77
|
-
return sections.filter((s) => prefixes.some((prefix) => s.label.startsWith(prefix)));
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
/** A sentence as its words, without the markdown around them: bold, code ticks, list marks and spacing. Pure. */
|
|
81
|
-
const sentenceWords = (sentence: string): string => sentence.replace(/[*`_]/g, '').replace(/^\s*(?:[-+]|\d+[.)])\s+/, '').replace(/\s+/g, ' ').trim();
|
|
82
|
-
|
|
83
|
-
/** A text's sentences of four words or more, each as its words without the stop that ends it. Pure. */
|
|
84
|
-
const sentencesOf = (text: string): ReadonlyArray<string> => text.split('\n')
|
|
85
|
-
.flatMap((line) => line.split(/(?<=[.!?:;])\s+(?=[*`"(A-Z])/))
|
|
86
|
-
.map((sentence) => sentenceWords(sentence).replace(/[.!?:;]+$/, ''))
|
|
87
|
-
.filter((sentence) => sentence.split(' ').length >= 4);
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* The sentences a change takes out of a skill that no synced skill holds after it: each sentence of `before` found
|
|
91
|
-
* neither in `after` nor in `elsewhere` (the other skills' text), compared by their words. A rule moved to another
|
|
92
|
-
* skill in the same change is not one of them only if that skill's text already holds it, which a change to one skill
|
|
93
|
-
* never writes: the 2026-11-20 move of a numbering rule out of senior-swe installed the deletion alone. Pure.
|
|
94
|
-
*/
|
|
95
|
-
export const sentencesRemoved = (input: { readonly before: string; readonly after: string; readonly elsewhere: string }): ReadonlyArray<string> => {
|
|
96
|
-
const kept = sentenceWords(`${input.after}\n${input.elsewhere}`.split('\n').map(sentenceWords).join(' '));
|
|
97
|
-
return [...new Set(sentencesOf(input.before))].filter((sentence) => !kept.includes(sentence));
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
/** A skill's length against the cap it states for itself ("**Cap: 200 lines.**"); none for a skill that states none. Pure. */
|
|
101
|
-
export const lineBudgetOf = (text: string): { readonly lines: number; readonly cap: number } | null => {
|
|
102
|
-
const cap = /\*\*Cap: (\d+) lines\.\*\*/.exec(text);
|
|
103
|
-
return cap === null ? null : { lines: text.split('\n').length - (text.endsWith('\n') ? 1 : 0), cap: Number(cap[1]) };
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
/** Applies each edit to `text`, refusing one whose `find` is missing or occurs more than once, or a result over the skill's own stated cap. Pure. */
|
|
107
|
-
export const applyEdits = (text: string, edits: ReadonlyArray<SkillEdit>): Result.Result<string, string> => {
|
|
108
|
-
let out = text;
|
|
109
|
-
for (const [i, e] of edits.entries()) {
|
|
110
|
-
const first = out.indexOf(e.find);
|
|
111
|
-
if (e.find.length === 0 || first < 0) return Result.fail(`edit ${i + 1}'s text to replace is not in the skill: ${e.find.slice(0, 120)}`);
|
|
112
|
-
if (out.indexOf(e.find, first + 1) >= 0) return Result.fail(`edit ${i + 1}'s text to replace occurs more than once: ${e.find.slice(0, 120)}`);
|
|
113
|
-
out = out.slice(0, first) + e.replace + out.slice(first + e.find.length);
|
|
114
|
-
}
|
|
115
|
-
const budget = lineBudgetOf(out);
|
|
116
|
-
if (budget !== null && budget.lines > budget.cap) return Result.fail(`the skill would have ${budget.lines} lines, over its own cap of ${budget.cap}`);
|
|
117
|
-
return Result.succeed(out);
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* One hash of every synced skill's text: what Classify and Draft read, so an item parked on its last outcome runs again
|
|
122
|
-
* once a skill it may draft on has changed (an install, or another machine's edit pulled).
|
|
123
|
-
*/
|
|
124
|
-
export const skillsTextSha = (root: string): string => shaOf(fs.readdirSync(root)
|
|
125
|
-
.filter((d) => !d.startsWith('.') && fs.existsSync(path.join(root, d, 'SKILL.md')))
|
|
126
|
-
.sort()
|
|
127
|
-
.map((d) => `${d}\n${fs.readFileSync(path.join(root, d, 'SKILL.md'), 'utf8')}`)
|
|
128
|
-
.join('\n'));
|
|
129
|
-
|
|
130
|
-
export interface ISkillFiles {
|
|
131
|
-
/** Every synced skill's sections. */
|
|
132
|
-
readonly sections: () => Effect.fn.Return<ReadonlyArray<SkillSection>, SkillFilesError>;
|
|
133
|
-
readonly skillText: (skill: string) => Effect.fn.Return<SkillText, SkillFilesError>;
|
|
134
|
-
/** The names of a skill's example files (`examples/*.md`), which name their topics. */
|
|
135
|
-
readonly exampleNames: (skill: string) => Effect.fn.Return<ReadonlyArray<string>, SkillFilesError>;
|
|
136
|
-
/**
|
|
137
|
-
* Installs a change: the skill's new text, then its history entry, its example file and its A/B case. skill-sync keeps
|
|
138
|
-
* the later of two edits to a file and drops the other, so an install on a copy that has not pulled another machine's
|
|
139
|
-
* edit would overwrite that edit everywhere: it first waits for this copy to pull the skill's latest synced edit. The
|
|
140
|
-
* text is written only while the skill still has the text `newText` was built on (`onSha`), checked again just before
|
|
141
|
-
* the write; otherwise it fails with `SkillChangedError` and writes nothing. Installing the same change again, after a
|
|
142
|
-
* `SkillChangedError`, adds no second history entry, example or case.
|
|
143
|
-
*/
|
|
144
|
-
readonly install: (input: {
|
|
145
|
-
readonly skill: string;
|
|
146
|
-
readonly onSha: string;
|
|
147
|
-
readonly newText: string;
|
|
148
|
-
readonly history: string;
|
|
149
|
-
readonly example: { readonly name: string; readonly text: string };
|
|
150
|
-
readonly evalCase: { readonly file: string; readonly json: string };
|
|
151
|
-
}) => Effect.fn.Return<Installed, SkillFilesError | SkillChangedError>;
|
|
152
|
-
/**
|
|
153
|
-
* Waits until skill-sync's server lists the skill edited at or after `since` (unix ms), which means every machine pulls
|
|
154
|
-
* the installed text, and checks the copy still holds `afterSha`; another machine's later edit that replaced it fails
|
|
155
|
-
* with `SkillChangedError`. Gives the synced list's line for it.
|
|
156
|
-
*/
|
|
157
|
-
readonly confirmSynced: (input: { readonly skill: string; readonly since: number; readonly afterSha: string }) => Effect.fn.Return<string, SkillFilesError | SkillChangedError>;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
export class SkillFiles extends Context.Service<SkillFiles, ISkillFiles>()('SkillFiles') {}
|
|
161
|
-
|
|
162
|
-
const attempt = <A>(what: string, f: () => A) => Effect.try({ try: f, catch: (e) => new SkillFilesError({ reason: `${what}: ${e instanceof Error ? e.message : String(e)}` }) });
|
|
163
|
-
|
|
164
|
-
class SkillFolder implements ISkillFiles {
|
|
165
|
-
constructor(private readonly root: string, private readonly syncedSkills: SyncedSkills, private readonly pullWait: PullWait) {}
|
|
166
|
-
|
|
167
|
-
private *syncedEdit(skill: string): Effect.fn.Return<SyncedEdit | null, SkillFilesError> {
|
|
168
|
-
const skills = yield* Effect.tryPromise({ try: this.syncedSkills, catch: (e) => new SkillFilesError({ reason: `the synced list could not be read: ${e instanceof Error ? e.message : String(e)}` }) });
|
|
169
|
-
return syncedEditOf(skills, skill);
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
*sections(): Effect.fn.Return<ReadonlyArray<SkillSection>, SkillFilesError> {
|
|
173
|
-
const skills = yield* attempt('the skills folder could not be listed', () =>
|
|
174
|
-
fs.readdirSync(this.root).filter((d) => !d.startsWith('.') && fs.existsSync(path.join(this.root, d, 'SKILL.md'))).sort());
|
|
175
|
-
const out: SkillSection[] = [];
|
|
176
|
-
for (const skill of skills) out.push(...sectionsOf(skill, (yield* this.skillText(skill)).text));
|
|
177
|
-
return out;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
*skillText(skill: string): Effect.fn.Return<SkillText, SkillFilesError> {
|
|
181
|
-
const text = yield* attempt(`skill ${skill} could not be read`, () => fs.readFileSync(path.join(this.root, skill, 'SKILL.md'), 'utf8'));
|
|
182
|
-
return { skill, text, sha: shaOf(text) };
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
*exampleNames(skill: string): Effect.fn.Return<ReadonlyArray<string>, SkillFilesError> {
|
|
186
|
-
const dir = path.join(this.root, skill, 'examples');
|
|
187
|
-
return yield* attempt(`skill ${skill}'s examples could not be listed`, () => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort() : []));
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** The skill's latest synced edit that this copy has not pulled yet, after waiting up to `pullWait` for the pull; none once pulled. */
|
|
191
|
-
private *unpulledEdit(skill: string): Effect.fn.Return<SyncedEdit | null, SkillFilesError> {
|
|
192
|
-
const dir = path.join(this.root, skill);
|
|
193
|
-
for (let tries = 0; ; tries++) {
|
|
194
|
-
const synced = yield* this.syncedEdit(skill);
|
|
195
|
-
const pulled = yield* attempt(`skill ${skill}'s files could not be listed`, () => newestEdit(dir));
|
|
196
|
-
// A pulled file takes the server's edit time, so a server edit later than every file here has not been pulled yet.
|
|
197
|
-
if (synced === null || Math.floor(synced.at / 1000) <= Math.floor(pulled / 1000)) return null;
|
|
198
|
-
if (tries >= this.pullWait.tries) return synced;
|
|
199
|
-
yield* Effect.sleep(this.pullWait.interval);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
*install(input: Parameters<ISkillFiles['install']>[0]): Effect.fn.Return<Installed, SkillFilesError | SkillChangedError> {
|
|
204
|
-
const unpulled = yield* this.unpulledEdit(input.skill);
|
|
205
|
-
if (unpulled !== null) return yield* Effect.fail(new SkillFilesError({ reason: `skill ${input.skill} has a synced edit from ${unpulled.machine} at ${new Date(unpulled.at).toISOString()} that this copy has not pulled yet` }));
|
|
206
|
-
const before = yield* this.skillText(input.skill);
|
|
207
|
-
const changed = () => new SkillChangedError({ skill: input.skill, reason: `skill ${input.skill} changed while the change was being made on it` });
|
|
208
|
-
if (before.sha !== input.onSha) return yield* Effect.fail(changed());
|
|
209
|
-
const dir = path.join(this.root, input.skill);
|
|
210
|
-
const skillFile = path.join(dir, 'SKILL.md');
|
|
211
|
-
const historyFile = path.join(dir, 'history.md');
|
|
212
|
-
const exampleFile = path.join(dir, 'examples', input.example.name);
|
|
213
|
-
const caseFile = path.join(this.root, 'agentic-collaboration', 'evals', 'cases', input.evalCase.file);
|
|
214
|
-
/** A file this change writes may already hold what it writes, from an earlier try of the same install; any other content is not its own. */
|
|
215
|
-
const holdsOther = (file: string, text: string) => fs.existsSync(file) && fs.readFileSync(file, 'utf8') !== text;
|
|
216
|
-
yield* attempt('the change could not be written', () => {
|
|
217
|
-
if (holdsOther(exampleFile, input.example.text)) throw new Error(`example ${input.example.name} already exists`);
|
|
218
|
-
if (holdsOther(caseFile, input.evalCase.json)) throw new Error(`A/B case ${input.evalCase.file} already exists`);
|
|
219
|
-
});
|
|
220
|
-
// Written beside it, then renamed over it, so no reader ever sees half a skill; the text is checked once more right
|
|
221
|
-
// before the rename, so an edit that landed while the change was being made is never overwritten.
|
|
222
|
-
const next = `${skillFile}.installing`;
|
|
223
|
-
const landed = yield* attempt('the change could not be written', () => {
|
|
224
|
-
fs.writeFileSync(next, input.newText);
|
|
225
|
-
if (shaOf(fs.readFileSync(skillFile, 'utf8')) !== input.onSha) {
|
|
226
|
-
fs.rmSync(next);
|
|
227
|
-
return false;
|
|
228
|
-
}
|
|
229
|
-
fs.renameSync(next, skillFile);
|
|
230
|
-
return true;
|
|
231
|
-
});
|
|
232
|
-
if (!landed) return yield* Effect.fail(changed());
|
|
233
|
-
yield* attempt('the change could not be written', () => {
|
|
234
|
-
const history = input.history.trim();
|
|
235
|
-
if (!fs.readFileSync(historyFile, 'utf8').includes(history)) fs.appendFileSync(historyFile, `\n${history}\n`);
|
|
236
|
-
fs.mkdirSync(path.dirname(exampleFile), { recursive: true });
|
|
237
|
-
fs.writeFileSync(exampleFile, input.example.text);
|
|
238
|
-
fs.writeFileSync(caseFile, input.evalCase.json);
|
|
239
|
-
});
|
|
240
|
-
return { skill: input.skill, beforeSha: before.sha, afterSha: shaOf(input.newText), wordsBefore: words(before.text), wordsAfter: words(input.newText), files: [skillFile, historyFile, exampleFile, caseFile] };
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
*confirmSynced(input: { readonly skill: string; readonly since: number; readonly afterSha: string }): Effect.fn.Return<string, SkillFilesError | SkillChangedError> {
|
|
244
|
-
for (let tries = 0; tries < 10; tries++) {
|
|
245
|
-
const synced = yield* this.syncedEdit(input.skill);
|
|
246
|
-
// The list shows seconds; an edit in the same second as the install counts.
|
|
247
|
-
if (synced !== null && Math.floor(synced.at / 1000) >= Math.floor(input.since / 1000)) {
|
|
248
|
-
const now = (yield* this.skillText(input.skill)).sha;
|
|
249
|
-
if (now !== input.afterSha) return yield* Effect.fail(new SkillChangedError({ skill: input.skill, reason: `skill ${input.skill} no longer holds the installed text: an edit from ${synced.machine} replaced it` }));
|
|
250
|
-
return synced.line;
|
|
251
|
-
}
|
|
252
|
-
yield* Effect.sleep('15 seconds');
|
|
253
|
-
}
|
|
254
|
-
return yield* Effect.fail(new SkillFilesError({ reason: `the synced list never showed ${input.skill} edited after the install at ${new Date(input.since).toISOString()}` }));
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** The synced list as skill-sync's server holds it, read by the daemon this runs in. */
|
|
259
|
-
export type SyncedSkills = () => Promise<ReadonlyArray<ListedSkill>>;
|
|
260
|
-
|
|
261
|
-
/** A skill's last synced edit: when (unix ms) and on which machine, and the line naming it for an install's record. */
|
|
262
|
-
export interface SyncedEdit {
|
|
263
|
-
readonly at: number;
|
|
264
|
-
readonly machine: string;
|
|
265
|
-
readonly line: string;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/** A skill's last synced edit in the synced list; none for a skill not on it or with no files yet. Pure. */
|
|
269
|
-
export const syncedEditOf = (skills: ReadonlyArray<ListedSkill>, skill: string): SyncedEdit | null => {
|
|
270
|
-
const listed = skills.find((s) => s.name === skill);
|
|
271
|
-
if (listed === undefined || listed.editedAt === null || listed.editedBy === null) return null;
|
|
272
|
-
return { at: listed.editedAt, machine: listed.editedBy, line: `${skill}: ${listed.files} files, last edited ${new Date(listed.editedAt).toISOString()} on ${listed.editedBy}` };
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
/** The latest modification time (unix ms) of any file skill-sync copies in a folder: none under a name starting with a dot. */
|
|
276
|
-
const newestEdit = (dir: string): number => fs.readdirSync(dir, { recursive: true, withFileTypes: true })
|
|
277
|
-
.filter((e) => e.isFile() && !path.relative(dir, path.join(e.parentPath, e.name)).split(path.sep).some((part) => part.startsWith('.')))
|
|
278
|
-
.reduce((latest, e) => Math.max(latest, fs.statSync(path.join(e.parentPath, e.name)).mtimeMs), 0);
|
|
279
|
-
|
|
280
|
-
/** How long an install waits for this copy to pull a synced edit of the skill it has not pulled yet: `tries` more reads of the list, `interval` apart. */
|
|
281
|
-
export interface PullWait {
|
|
282
|
-
readonly tries: number;
|
|
283
|
-
readonly interval: Duration.Input;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/** Two minutes: an edit another machine pushes normally reaches this copy within seconds; one still missing after that is left to the item's next run. */
|
|
287
|
-
const PULL_WAIT: PullWait = { tries: 8, interval: '15 seconds' };
|
|
288
|
-
|
|
289
|
-
export const SkillFilesLive = (input: { readonly root: string; readonly syncedSkills: SyncedSkills; readonly pullWait?: PullWait }) =>
|
|
290
|
-
Layer.succeed(SkillFiles, new SkillFolder(input.root, input.syncedSkills, input.pullWait ?? PULL_WAIT));
|