@jive-sh/skill-sync 0.7.0 → 0.7.1-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.
Files changed (107) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -36
  3. package/README.md +0 -187
  4. package/bin/package.json +0 -1
  5. package/bin/skill-sync +0 -614
  6. package/bin/skill-sync-daemon +0 -614
  7. package/dist/daemons/skill-sync-daemon.js +0 -634
  8. package/dist/daemons/skill-sync-daemon.js.map +0 -1
  9. package/dist/entrypoints/skill-sync.js +0 -7
  10. package/dist/entrypoints/skill-sync.js.map +0 -1
  11. package/dist/index.js +0 -10
  12. package/dist/index.js.map +0 -1
  13. package/dist/internal/agents/agent-tool.js +0 -102
  14. package/dist/internal/agents/agent-tool.js.map +0 -1
  15. package/dist/internal/agents/claude.js +0 -424
  16. package/dist/internal/agents/claude.js.map +0 -1
  17. package/dist/internal/agents/codex.js +0 -270
  18. package/dist/internal/agents/codex.js.map +0 -1
  19. package/dist/internal/agents/command.js +0 -219
  20. package/dist/internal/agents/command.js.map +0 -1
  21. package/dist/internal/agents/grok.js +0 -170
  22. package/dist/internal/agents/grok.js.map +0 -1
  23. package/dist/internal/agents/index.js +0 -70
  24. package/dist/internal/agents/index.js.map +0 -1
  25. package/dist/internal/cli.js +0 -185
  26. package/dist/internal/cli.js.map +0 -1
  27. package/dist/internal/config.js +0 -131
  28. package/dist/internal/config.js.map +0 -1
  29. package/dist/internal/control.js +0 -113
  30. package/dist/internal/control.js.map +0 -1
  31. package/dist/internal/daemon-control/impl.js +0 -68
  32. package/dist/internal/daemon-control/impl.js.map +0 -1
  33. package/dist/internal/daemon-control/interface.js +0 -4
  34. package/dist/internal/daemon-control/interface.js.map +0 -1
  35. package/dist/internal/folders.js +0 -47
  36. package/dist/internal/folders.js.map +0 -1
  37. package/dist/internal/local-skills.js +0 -43
  38. package/dist/internal/local-skills.js.map +0 -1
  39. package/dist/internal/path.js +0 -36
  40. package/dist/internal/path.js.map +0 -1
  41. package/dist/internal/server.js +0 -80
  42. package/dist/internal/server.js.map +0 -1
  43. package/dist/internal/skill-check.js +0 -83
  44. package/dist/internal/skill-check.js.map +0 -1
  45. package/dist/internal/skill-refinement/evals/cases.js +0 -143
  46. package/dist/internal/skill-refinement/evals/cases.js.map +0 -1
  47. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
  48. package/dist/internal/skill-refinement/evals/opus-judge-original.json +0 -165
  49. package/dist/internal/skill-refinement/feedback/intake.js +0 -52
  50. package/dist/internal/skill-refinement/feedback/intake.js.map +0 -1
  51. package/dist/internal/skill-refinement/jev/impl.js +0 -51
  52. package/dist/internal/skill-refinement/jev/impl.js.map +0 -1
  53. package/dist/internal/skill-refinement/jev/interface.js +0 -14
  54. package/dist/internal/skill-refinement/jev/interface.js.map +0 -1
  55. package/dist/internal/skill-refinement/paths.js +0 -62
  56. package/dist/internal/skill-refinement/paths.js.map +0 -1
  57. package/dist/internal/skill-refinement/platform.js +0 -68
  58. package/dist/internal/skill-refinement/platform.js.map +0 -1
  59. package/dist/internal/skill-refinement/service.js +0 -228
  60. package/dist/internal/skill-refinement/service.js.map +0 -1
  61. package/dist/internal/skill-refinement/skills/skill-text.js +0 -137
  62. package/dist/internal/skill-refinement/skills/skill-text.js.map +0 -1
  63. package/dist/internal/skill-refinement/workflow/skill-refinement.js +0 -398
  64. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +0 -1
  65. package/dist/internal/skill-refinement/writer/impl.js +0 -69
  66. package/dist/internal/skill-refinement/writer/impl.js.map +0 -1
  67. package/dist/internal/skill-refinement/writer/interface.js +0 -10
  68. package/dist/internal/skill-refinement/writer/interface.js.map +0 -1
  69. package/dist/internal/sync.js +0 -182
  70. package/dist/internal/sync.js.map +0 -1
  71. package/dist/internal/wire.js +0 -31
  72. package/dist/internal/wire.js.map +0 -1
  73. package/install.cjs +0 -614
  74. package/src/daemons/skill-sync-daemon.ts +0 -639
  75. package/src/entrypoints/skill-sync.ts +0 -12
  76. package/src/index.ts +0 -15
  77. package/src/internal/agents/agent-tool.ts +0 -149
  78. package/src/internal/agents/claude.ts +0 -442
  79. package/src/internal/agents/codex.ts +0 -288
  80. package/src/internal/agents/command.ts +0 -257
  81. package/src/internal/agents/grok.ts +0 -174
  82. package/src/internal/agents/index.ts +0 -74
  83. package/src/internal/cli.ts +0 -217
  84. package/src/internal/config.ts +0 -172
  85. package/src/internal/control.ts +0 -157
  86. package/src/internal/daemon-control/impl.ts +0 -80
  87. package/src/internal/daemon-control/interface.ts +0 -40
  88. package/src/internal/folders.ts +0 -50
  89. package/src/internal/local-skills.ts +0 -58
  90. package/src/internal/path.ts +0 -32
  91. package/src/internal/server.ts +0 -76
  92. package/src/internal/skill-check.ts +0 -97
  93. package/src/internal/skill-refinement/evals/cases.ts +0 -167
  94. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
  95. package/src/internal/skill-refinement/evals/opus-judge-original.json +0 -165
  96. package/src/internal/skill-refinement/feedback/intake.ts +0 -66
  97. package/src/internal/skill-refinement/jev/impl.ts +0 -63
  98. package/src/internal/skill-refinement/jev/interface.ts +0 -51
  99. package/src/internal/skill-refinement/paths.ts +0 -87
  100. package/src/internal/skill-refinement/platform.ts +0 -72
  101. package/src/internal/skill-refinement/service.ts +0 -274
  102. package/src/internal/skill-refinement/skills/skill-text.ts +0 -199
  103. package/src/internal/skill-refinement/workflow/skill-refinement.ts +0 -430
  104. package/src/internal/skill-refinement/writer/impl.ts +0 -79
  105. package/src/internal/skill-refinement/writer/interface.ts +0 -29
  106. package/src/internal/sync.ts +0 -216
  107. package/src/internal/wire.ts +0 -439
@@ -1,274 +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
- describeFailure, KEEP_RUNNING_EVERY_SECONDS, newRunId, oneTurnAtATime, planRunStarts, runsNow, SET_WORKFLOW_BUDGET_SQL, SET_WORKFLOW_RUNS_SQL,
15
- START_LIMIT_SECONDS, TURN_LIMIT_MS, WORKFLOW_BUDGET_SQL,
16
- } from '@jive-sh/workflow-platform';
17
- import { Database } from 'bun:sqlite';
18
- import { Crypto, Duration, Effect, Layer, ManagedRuntime, Option, pipe } from 'effect';
19
- import { ClusterWorkflowEngine, RunnerAddress, SingleRunner } from 'effect/cluster';
20
- import fs from 'node:fs';
21
- import os from 'node:os';
22
- import path from 'node:path';
23
- import { judgeVersion } from './evals/cases';
24
- import { makeIntake } from './feedback/intake';
25
- import { JevLive } from './jev/impl';
26
- import { engineDatabase, installedFolder, intakeFolder, locateSkillCopy, machineIntakeFolders, platformDatabase, runFolder, type WorkflowFolders } from './paths';
27
- import OPUS_JUDGE_ORIGINAL from './evals/opus-judge-original.json';
28
- import OPUS_ACTION_JUDGE_ORIGINAL from './evals/opus-action-judge-original.json';
29
- import { skillRefinementPlatform } from './platform';
30
- import { SkillFiles, SkillFilesLive, type SyncedSkills } from './skills/skill-text';
31
- import type { Jev } from './jev/interface';
32
- import type { Writer } from './writer/interface';
33
- import { defineSkillRefinement, WORKFLOW } from './workflow/skill-refinement';
34
- import { WriterLive } from './writer/impl';
35
- import type { LimitChange, RefinementPageData } from '../wire';
36
-
37
- /** Bun's WebCrypto, as the cluster's message storage needs it. */
38
- const CryptoLive = Layer.succeed(Crypto.Crypto, Crypto.make({
39
- randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)),
40
- digest: (algorithm, data) => Effect.promise(async () => new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, new Uint8Array(data)))),
41
- }));
42
-
43
- export interface ServiceConfig {
44
- readonly folders: WorkflowFolders;
45
- /** Jev's API key, read when used; empty while none is set, so its steps fail with that reason. */
46
- readonly typesafeApiKey: () => string;
47
- readonly jevModel: string;
48
- readonly claudeConfigDir: string;
49
- readonly writerModel: string;
50
- /** The Opus judge's grades of the original replies, the bar Jev is calibrated against. */
51
- readonly opusJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
52
- /** The evals' original action-judge prompt's grades of the action originals, the bar the action judge is held to. */
53
- readonly opusActionJudgeGrades: ReadonlyArray<{ readonly case: string; readonly pass: boolean }>;
54
- /** Every intake the items are read from (`machineIntakeFolders`). */
55
- readonly intakes: ReadonlyArray<string>;
56
- }
57
-
58
- /**
59
- * EACH WORKFLOW STARTS AT ONE RUN AND ONE AGENT (`spawn-subthread` section 2, step 3): set once, never changed here; the
60
- * owner changes them in the `workflow_budgets` table.
61
- */
62
- const ensureLimits = (folders: WorkflowFolders) => {
63
- const db = new Database(platformDatabase(folders), { create: true });
64
- try {
65
- db.run('CREATE TABLE IF NOT EXISTS workflow_budgets (workflow TEXT PRIMARY KEY, budget INTEGER NOT NULL, runs INTEGER, changed_at REAL NOT NULL)');
66
- if (db.query(WORKFLOW_BUDGET_SQL).get(WORKFLOW) === null) {
67
- db.query(SET_WORKFLOW_BUDGET_SQL).run(WORKFLOW, 1, Date.now() / 1000);
68
- db.query(SET_WORKFLOW_RUNS_SQL).run(WORKFLOW, 1, Date.now() / 1000);
69
- }
70
- } finally {
71
- db.close();
72
- }
73
- };
74
-
75
- /** The workflow, its engine and its modules, on one machine's folders; a test gives fake modules. */
76
- export const makeService = (config: ServiceConfig, modules: Layer.Layer<Jev | Writer | SkillFiles>) => {
77
- const { folders } = config;
78
- fs.mkdirSync(intakeFolder(folders), { recursive: true });
79
- ensureLimits(folders);
80
- const platform = skillRefinementPlatform(folders);
81
- const intake = makeIntake({ intake: intakeFolder(folders), intakes: config.intakes, installed: installedFolder(folders) });
82
- // A key put in place changes every task's inputs, so the items its absence stopped are queued again.
83
- const configFingerprint = () => JSON.stringify({ judge: judgeVersion(), jev: config.jevModel, jevKeySet: config.typesafeApiKey().length > 0, writer: config.writerModel, account: config.claudeConfigDir });
84
- const maintenance = defineSkillRefinement({ platform, intake, folders, opusJudgeGrades: config.opusJudgeGrades, opusActionJudgeGrades: config.opusActionJudgeGrades, configFingerprint });
85
- const layer = pipe(
86
- maintenance.layer as Layer.Layer<never>,
87
- Layer.provideMerge(ClusterWorkflowEngine.layer),
88
- Layer.provideMerge(SingleRunner.layer({
89
- runnerStorage: 'sql',
90
- shardingConfig: { runnerAddress: Option.some(RunnerAddress.make('skill-refinement', process.pid)), entityTerminationTimeout: Duration.minutes(10) },
91
- })),
92
- Layer.provideMerge(SqliteClient.layer({ filename: engineDatabase(folders), busyTimeout: Duration.seconds(1) })),
93
- Layer.provideMerge(CryptoLive),
94
- Layer.provideMerge(modules),
95
- );
96
- const runtime = ManagedRuntime.make(layer);
97
-
98
- /** One turn: the list read into the task queue, then the runs the limits keep, started and left to the engine. */
99
- const turn = oneTurnAtATime(async (stillCurrent) => {
100
- const declared = platform.steps.declaredWorkflows();
101
- for (const d of declared) {
102
- if (d.pending === undefined) continue;
103
- const work = await Effect.runPromise(d.pending());
104
- await Effect.runPromise(platform.tasks.recordListing(d.name, work));
105
- }
106
- const limits = await Effect.runPromise(platform.storage.budgets.limitsOf(WORKFLOW));
107
- const going = await Effect.runPromise(platform.storage.engine.runningRuns(WORKFLOW));
108
- const plans = planRunStarts({
109
- declared,
110
- limitsOf: () => limits ?? { agents: 0, runs: null },
111
- runningRuns: () => going,
112
- });
113
- for (const p of plans) {
114
- for (let i = 0; i < p.start; i++) {
115
- if (!stillCurrent()) return;
116
- const run = newRunId();
117
- try {
118
- await runtime.runPromise(Effect.timeout(Effect.asVoid(p.declaration.start(run)), `${START_LIMIT_SECONDS} seconds`));
119
- console.log(`[keep running] ${p.declaration.name}: started run ${run}`);
120
- } catch (e) {
121
- console.error(`[keep running] ${p.declaration.name}: run ${run} did not start: ${describeFailure(e)}`);
122
- }
123
- }
124
- }
125
- }, TURN_LIMIT_MS);
126
- const kick = () => { void turn().catch((e: unknown) => console.error(`[keep running] ${describeFailure(e)}`)); };
127
- platform.steps.onRunEnded(kick);
128
-
129
- return { platform, intake, runtime, turn, kick };
130
- };
131
-
132
- /** What the live modules need beyond the service's configuration: the `claude` CLI, and skill-sync's synced list. */
133
- export interface LiveInputs {
134
- readonly claudeCommand: string;
135
- readonly syncedSkills: SyncedSkills;
136
- }
137
-
138
- /** The live modules the workflow's steps call: Jev, the generative model and the synced skills. */
139
- export const liveModules = (config: ServiceConfig, live: LiveInputs): Layer.Layer<Jev | Writer | SkillFiles> => Layer.mergeAll(
140
- JevLive({ apiKey: config.typesafeApiKey, model: config.jevModel }),
141
- WriterLive({ claudeCommand: live.claudeCommand, claudeConfigDir: config.claudeConfigDir, model: config.writerModel, scratch: runFolder(config.folders, 'writer-scratch') }),
142
- SkillFilesLive({ root: config.folders.skills, syncedSkills: live.syncedSkills }),
143
- );
144
-
145
- /** The phase this machine's one workflow is shown under: the platform groups workflows by phase. */
146
- const PHASES = ['skills'] as const;
147
- /** The window of each workflow's figures, as the platform's dashboard states it. */
148
- const FIGURES_HOURS = 24;
149
- /** A runner whose heartbeat is older than this is gone, whatever its process does now. */
150
- const RUNNER_HEARTBEAT_STALE_MS = 60_000;
151
-
152
- /** The running workflow, as the daemon uses it. */
153
- export interface SkillRefinementRunner {
154
- /** The dashboard's data, all of it read at the call. */
155
- readonly pageData: () => Promise<RefinementPageData>;
156
- /** 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. */
157
- readonly setLimit: (r: LimitChange) => Promise<void>;
158
- /** Hands one feedback item to the workflow, in this machine's copy of the skill; gives its id. */
159
- readonly addFeedback: (r: { readonly slug: string; readonly text: string }) => Promise<string>;
160
- }
161
-
162
- /** Why this machine runs no workflow, in a line for the daemon's log and the dashboard. */
163
- export type NotRunning = { readonly notRunning: string };
164
-
165
- /**
166
- * Another live process running this workflow on the same engine database: the runner a machine had before the daemon
167
- * took the work over (`skill-refinement.service`), or a copy started by hand. Read from the engine's own runner
168
- * registrations, each named `<host>:<pid>` and heartbeating while it lives.
169
- */
170
- export const otherLiveRunner = (folders: WorkflowFolders, now: number): string | null => {
171
- const file = engineDatabase(folders);
172
- if (!fs.existsSync(file)) return null;
173
- const db = new Database(file, { readonly: true });
174
- try {
175
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'cluster_runners'`).get() === null) return null;
176
- const rows = db.query('SELECT address, last_heartbeat FROM cluster_runners').all() as ReadonlyArray<{ address: string; last_heartbeat: string }>;
177
- for (const row of rows) {
178
- const pid = Number(row.address.split(':').pop());
179
- const beat = Date.parse(`${row.last_heartbeat.replace(' ', 'T')}Z`);
180
- if (!Number.isInteger(pid) || pid === process.pid || Number.isNaN(beat) || now - beat > RUNNER_HEARTBEAT_STALE_MS) continue;
181
- try {
182
- process.kill(pid, 0);
183
- return `process ${pid} runs it (heartbeat ${new Date(beat).toISOString()})`;
184
- } catch {
185
- // Gone: its row is left from before.
186
- }
187
- }
188
- return null;
189
- } finally {
190
- db.close();
191
- }
192
- };
193
-
194
- /**
195
- * Starts the workflow on this machine's copy of the skill, once no other process runs it. Waits, checking every minute,
196
- * while one does, so the runner a machine had before hands over by stopping. Gives the runner, or why there is none.
197
- */
198
- export const startSkillRefinement = async (input: {
199
- readonly home: string;
200
- readonly claudeCommand: string | undefined;
201
- readonly syncedSkills: SyncedSkills;
202
- /** Called once the runner is up, and again with why whenever it is waiting or cannot run. */
203
- readonly onState: (state: SkillRefinementRunner | NotRunning) => void;
204
- }): Promise<void> => {
205
- const copy = locateSkillCopy({ home: input.home, claudeConfigDir: process.env.SKILL_REFINEMENT_CLAUDE_CONFIG_DIR });
206
- if (copy === null) return input.onState({ notRunning: 'this machine has no copy of the autonomous-skill-refinement skill' });
207
- if (input.claudeCommand === undefined) return input.onState({ notRunning: 'no `claude` CLI was found on this machine for the drafting and A/B steps' });
208
- let waitingFor = '';
209
- for (;;) {
210
- const other = otherLiveRunner(copy.folders, Date.now());
211
- if (other === null) break;
212
- if (other !== waitingFor) input.onState({ notRunning: `waiting to take over: ${other}` });
213
- waitingFor = other;
214
- await Bun.sleep(60_000);
215
- }
216
- const config: ServiceConfig = {
217
- folders: copy.folders,
218
- typesafeApiKey: () => process.env.TYPESAFE_API_KEY ?? (fs.existsSync(copy.jevKeyFile) ? fs.readFileSync(copy.jevKeyFile, 'utf8').trim() : ''),
219
- jevModel: 'jev-latest',
220
- claudeConfigDir: process.env.SKILL_REFINEMENT_CLAUDE_CONFIG_DIR ?? copy.accountFolder,
221
- writerModel: 'claude-opus-5-5',
222
- opusJudgeGrades: OPUS_JUDGE_ORIGINAL.grades,
223
- opusActionJudgeGrades: OPUS_ACTION_JUDGE_ORIGINAL.grades,
224
- intakes: machineIntakeFolders({ home: input.home, own: copy.folders }),
225
- };
226
- const service = makeService(config, liveModules(config, { claudeCommand: input.claudeCommand, syncedSkills: input.syncedSkills }));
227
- 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}`);
228
- // The engine starts with the runtime; resumed runs continue from their records.
229
- await service.runtime.runPromise(Effect.void);
230
- for (const folder of config.intakes) fs.watch(folder, () => service.kick());
231
- // The key's arrival changes every task's inputs (`configFingerprint`), which no note or listing announces: the waiting Pick is woken to read them.
232
- fs.watch(copy.skillFolder, (_, file) => { if (file === path.basename(copy.jevKeyFile)) service.platform.wakes.wakePicksOf(WORKFLOW, 'the Jev key was set'); });
233
- setInterval(service.kick, KEEP_RUNNING_EVERY_SECONDS * 1000);
234
- service.kick();
235
-
236
- const { platform } = service;
237
- // Each queue counted when it may have changed, for the dashboard's queues over time; only the process running the workflow records them.
238
- platform.queueCounts.record((count) => service.runtime.runPromise(count));
239
- input.onState({
240
- pageData: async () => {
241
- const now = Date.now() / 1000;
242
- const declared = platform.steps.declaredWorkflows();
243
- const unfinished = await Effect.runPromise(platform.storage.engine.unfinishedRuns());
244
- const newest = await Effect.runPromise(platform.storage.stepRecords.newestStepRecords(unfinished.map((u) => u.run)));
245
- const figures: Record<string, object> = {};
246
- for (const d of declared) {
247
- const read = await Effect.runPromise(platform.figures({ workflow: d.name, now, hours: FIGURES_HOURS }));
248
- if (read !== null) figures[d.name] = read;
249
- }
250
- return {
251
- view: await Effect.runPromise(platform.view({ now, phases: PHASES })),
252
- runsNow: runsNow({ phases: PHASES, undefinedPhase: 'skills', declared, unfinished, newest }),
253
- cpu: { limit: os.cpus().length, use: null },
254
- figures,
255
- };
256
- },
257
- setLimit: async ({ workflow, limit, value }) => {
258
- if (!platform.steps.declaredWorkflows().some((d) => d.name === workflow)) throw new Error(`no workflow ${workflow} runs here`);
259
- if (value !== null && (!Number.isInteger(value) || value < 0)) throw new Error(`a limit is a whole number of 0 or more, not ${value}`);
260
- if (value === null && limit === 'agents') throw new Error('the agents\' limit needs a number');
261
- const db = new Database(platformDatabase(copy.folders));
262
- try {
263
- db.query(limit === 'runs' ? SET_WORKFLOW_RUNS_SQL : SET_WORKFLOW_BUDGET_SQL).run(workflow, value, Date.now() / 1000);
264
- } finally {
265
- db.close();
266
- }
267
- // A run past a lower limit stands down at its next agent step; a higher one starts more at once.
268
- platform.wakes.runPlanChanged({ workflow, source: `its ${limit === 'runs' ? 'run' : 'agents\''} limit set from the dashboard` });
269
- service.kick();
270
- console.log(`[skill refinement] ${workflow}: ${limit} limit set to ${String(value)} from the dashboard`);
271
- },
272
- addFeedback: ({ slug, text }) => Effect.runPromise(service.intake.add({ arrived: new Date(), slug, text })),
273
- });
274
- };
@@ -1,199 +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, 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
- export const shaOf = (text: string): string => new Bun.CryptoHasher('sha256').update(text).digest('hex');
45
- const words = (text: string): number => text.split(/\s+/).filter(Boolean).length;
46
-
47
- /** A skill's sections: each `##` heading, and each `###` under it as `heading › subheading`. Pure. */
48
- export const sectionsOf = (skill: string, text: string): ReadonlyArray<SkillSection> => {
49
- const out: Array<{ label: string; lines: string[] }> = [];
50
- let h2: string | null = null;
51
- for (const line of text.split('\n')) {
52
- const two = /^## (.+)$/.exec(line);
53
- const three = /^### (.+)$/.exec(line);
54
- if (two !== null) { h2 = two[1]!.trim(); out.push({ label: `${skill} § ${h2}`, lines: [] }); continue; }
55
- if (three !== null) { out.push({ label: `${skill} § ${h2 ?? '(top)'} › ${three[1]!.trim()}`, lines: [] }); continue; }
56
- out[out.length - 1]?.lines.push(line);
57
- }
58
- return out.map((s) => ({ skill, label: s.label, text: s.lines.join('\n').trim() })).filter((s) => s.text.length > 0);
59
- };
60
-
61
- /** 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. */
62
- export const applyEdits = (text: string, edits: ReadonlyArray<SkillEdit>): Result.Result<string, string> => {
63
- let out = text;
64
- for (const [i, e] of edits.entries()) {
65
- const first = out.indexOf(e.find);
66
- 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)}`);
67
- 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)}`);
68
- out = out.slice(0, first) + e.replace + out.slice(first + e.find.length);
69
- }
70
- // A skill that states its own length cap ("**Cap: 200 lines.**") is held to it: a change that leaves it longer does not apply.
71
- const cap = /\*\*Cap: (\d+) lines\.\*\*/.exec(out);
72
- const lines = out.split('\n').length - (out.endsWith('\n') ? 1 : 0);
73
- if (cap !== null && lines > Number(cap[1])) return Result.fail(`the skill would have ${lines} lines, over its own cap of ${cap[1]}`);
74
- return Result.succeed(out);
75
- };
76
-
77
- export interface ISkillFiles {
78
- /** Every synced skill's sections. */
79
- readonly sections: () => Effect.fn.Return<ReadonlyArray<SkillSection>, SkillFilesError>;
80
- readonly skillText: (skill: string) => Effect.fn.Return<SkillText, SkillFilesError>;
81
- /** The names of a skill's example files (`examples/*.md`), which name their topics. */
82
- readonly exampleNames: (skill: string) => Effect.fn.Return<ReadonlyArray<string>, SkillFilesError>;
83
- /**
84
- * Installs a change: the skill's new text, written only if the skill still has the text it was drafted on and this
85
- * copy holds the skill's latest synced edit, then its history entry, its example file and its A/B case. skill-sync keeps
86
- * 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
87
- * edit would overwrite that edit everywhere.
88
- */
89
- readonly install: (input: {
90
- readonly skill: string;
91
- readonly draftedOn: string;
92
- readonly newText: string;
93
- readonly history: string;
94
- readonly example: { readonly name: string; readonly text: string };
95
- readonly evalCase: { readonly file: string; readonly json: string };
96
- }) => Effect.fn.Return<Installed, SkillFilesError>;
97
- /**
98
- * Waits until skill-sync's server lists the skill edited at or after `since` (unix ms), which means every machine pulls
99
- * the installed text, and checks the copy still holds `afterSha` (another machine's later edit would have replaced it);
100
- * gives the synced list's line for it.
101
- */
102
- readonly confirmSynced: (input: { readonly skill: string; readonly since: number; readonly afterSha: string }) => Effect.fn.Return<string, SkillFilesError>;
103
- }
104
-
105
- export class SkillFiles extends Context.Service<SkillFiles, ISkillFiles>()('SkillFiles') {}
106
-
107
- const attempt = <A>(what: string, f: () => A) => Effect.try({ try: f, catch: (e) => new SkillFilesError({ reason: `${what}: ${e instanceof Error ? e.message : String(e)}` }) });
108
-
109
- class SkillFolder implements ISkillFiles {
110
- constructor(private readonly root: string, private readonly syncedSkills: SyncedSkills) {}
111
-
112
- private *syncedEdit(skill: string): Effect.fn.Return<SyncedEdit | null, SkillFilesError> {
113
- 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)}` }) });
114
- return syncedEditOf(skills, skill);
115
- }
116
-
117
- *sections(): Effect.fn.Return<ReadonlyArray<SkillSection>, SkillFilesError> {
118
- const skills = yield* attempt('the skills folder could not be listed', () =>
119
- fs.readdirSync(this.root).filter((d) => !d.startsWith('.') && fs.existsSync(path.join(this.root, d, 'SKILL.md'))).sort());
120
- const out: SkillSection[] = [];
121
- for (const skill of skills) out.push(...sectionsOf(skill, (yield* this.skillText(skill)).text));
122
- return out;
123
- }
124
-
125
- *skillText(skill: string): Effect.fn.Return<SkillText, SkillFilesError> {
126
- const text = yield* attempt(`skill ${skill} could not be read`, () => fs.readFileSync(path.join(this.root, skill, 'SKILL.md'), 'utf8'));
127
- return { skill, text, sha: shaOf(text) };
128
- }
129
-
130
- *exampleNames(skill: string): Effect.fn.Return<ReadonlyArray<string>, SkillFilesError> {
131
- const dir = path.join(this.root, skill, 'examples');
132
- return yield* attempt(`skill ${skill}'s examples could not be listed`, () => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort() : []));
133
- }
134
-
135
- *install(input: Parameters<ISkillFiles['install']>[0]): Effect.fn.Return<Installed, SkillFilesError> {
136
- const before = yield* this.skillText(input.skill);
137
- if (before.sha !== input.draftedOn) return yield* Effect.fail(new SkillFilesError({ reason: `skill ${input.skill} changed since the candidate was drafted on it; the next run drafts on its new text` }));
138
- const dir = path.join(this.root, input.skill);
139
- const synced = yield* this.syncedEdit(input.skill);
140
- const pulled = yield* attempt(`skill ${input.skill}'s files could not be listed`, () => newestEdit(dir));
141
- // A pulled file takes the server's edit time, so a server edit later than every file here has not been pulled yet.
142
- if (synced !== null && Math.floor(synced.at / 1000) > Math.floor(pulled / 1000)) return yield* Effect.fail(new SkillFilesError({ reason: `skill ${input.skill} has a synced edit from ${synced.machine} at ${new Date(synced.at).toISOString()} that this copy has not pulled yet; the next run drafts on it` }));
143
- const skillFile = path.join(dir, 'SKILL.md');
144
- const historyFile = path.join(dir, 'history.md');
145
- const exampleFile = path.join(dir, 'examples', input.example.name);
146
- const caseFile = path.join(this.root, 'agentic-collaboration', 'evals', 'cases', input.evalCase.file);
147
- yield* attempt('the change could not be written', () => {
148
- if (fs.existsSync(exampleFile)) throw new Error(`example ${input.example.name} already exists`);
149
- if (fs.existsSync(caseFile)) throw new Error(`A/B case ${input.evalCase.file} already exists`);
150
- // Written beside it, then renamed over it, so no reader ever sees half a skill.
151
- const next = `${skillFile}.installing`;
152
- fs.writeFileSync(next, input.newText);
153
- fs.renameSync(next, skillFile);
154
- fs.appendFileSync(historyFile, `\n${input.history.trim()}\n`);
155
- fs.mkdirSync(path.dirname(exampleFile), { recursive: true });
156
- fs.writeFileSync(exampleFile, input.example.text);
157
- fs.writeFileSync(caseFile, input.evalCase.json);
158
- });
159
- return { skill: input.skill, beforeSha: before.sha, afterSha: shaOf(input.newText), wordsBefore: words(before.text), wordsAfter: words(input.newText), files: [skillFile, historyFile, exampleFile, caseFile] };
160
- }
161
-
162
- *confirmSynced(input: { readonly skill: string; readonly since: number; readonly afterSha: string }): Effect.fn.Return<string, SkillFilesError> {
163
- for (let tries = 0; tries < 10; tries++) {
164
- const synced = yield* this.syncedEdit(input.skill);
165
- // The list shows seconds; an edit in the same second as the install counts.
166
- if (synced !== null && Math.floor(synced.at / 1000) >= Math.floor(input.since / 1000)) {
167
- const now = (yield* this.skillText(input.skill)).sha;
168
- if (now !== input.afterSha) return yield* Effect.fail(new SkillFilesError({ reason: `skill ${input.skill} no longer holds the installed text: an edit from ${synced.machine} replaced it` }));
169
- return synced.line;
170
- }
171
- yield* Effect.sleep('15 seconds');
172
- }
173
- return yield* Effect.fail(new SkillFilesError({ reason: `the synced list never showed ${input.skill} edited after the install at ${new Date(input.since).toISOString()}` }));
174
- }
175
- }
176
-
177
- /** The synced list as skill-sync's server holds it, read by the daemon this runs in. */
178
- export type SyncedSkills = () => Promise<ReadonlyArray<ListedSkill>>;
179
-
180
- /** A skill's last synced edit: when (unix ms) and on which machine, and the line naming it for an install's record. */
181
- export interface SyncedEdit {
182
- readonly at: number;
183
- readonly machine: string;
184
- readonly line: string;
185
- }
186
-
187
- /** A skill's last synced edit in the synced list; none for a skill not on it or with no files yet. Pure. */
188
- export const syncedEditOf = (skills: ReadonlyArray<ListedSkill>, skill: string): SyncedEdit | null => {
189
- const listed = skills.find((s) => s.name === skill);
190
- if (listed === undefined || listed.editedAt === null || listed.editedBy === null) return null;
191
- return { at: listed.editedAt, machine: listed.editedBy, line: `${skill}: ${listed.files} files, last edited ${new Date(listed.editedAt).toISOString()} on ${listed.editedBy}` };
192
- };
193
-
194
- /** The latest modification time (unix ms) of any file skill-sync copies in a folder: none under a name starting with a dot. */
195
- const newestEdit = (dir: string): number => fs.readdirSync(dir, { recursive: true, withFileTypes: true })
196
- .filter((e) => e.isFile() && !path.relative(dir, path.join(e.parentPath, e.name)).split(path.sep).some((part) => part.startsWith('.')))
197
- .reduce((latest, e) => Math.max(latest, fs.statSync(path.join(e.parentPath, e.name)).mtimeMs), 0);
198
-
199
- export const SkillFilesLive = (input: { readonly root: string; readonly syncedSkills: SyncedSkills }) => Layer.succeed(SkillFiles, new SkillFolder(input.root, input.syncedSkills));