@jive-sh/skill-sync 0.11.0-latest-darwin-x64 → 0.11.0

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 (236) hide show
  1. package/README.md +346 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +34 -0
  4. package/bin/skill-sync-daemon +34 -0
  5. package/dist/daemons/skill-sync-daemon.js +664 -0
  6. package/dist/daemons/skill-sync-daemon.js.map +1 -0
  7. package/dist/entrypoints/skill-sync.js +7 -0
  8. package/dist/entrypoints/skill-sync.js.map +1 -0
  9. package/dist/index.js +10 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/internal/agents/agent-tool.js +102 -0
  12. package/dist/internal/agents/agent-tool.js.map +1 -0
  13. package/dist/internal/agents/claude.js +424 -0
  14. package/dist/internal/agents/claude.js.map +1 -0
  15. package/dist/internal/agents/codex.js +270 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +219 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +170 -0
  20. package/dist/internal/agents/grok.js.map +1 -0
  21. package/dist/internal/agents/index.js +70 -0
  22. package/dist/internal/agents/index.js.map +1 -0
  23. package/dist/internal/cli.js +218 -0
  24. package/dist/internal/cli.js.map +1 -0
  25. package/dist/internal/comment-watch/held.js +14 -0
  26. package/dist/internal/comment-watch/held.js.map +1 -0
  27. package/dist/internal/comment-watch/key.js +4 -0
  28. package/dist/internal/comment-watch/key.js.map +1 -0
  29. package/dist/internal/comment-watch/message.js +37 -0
  30. package/dist/internal/comment-watch/message.js.map +1 -0
  31. package/dist/internal/comment-watch/paths.js +16 -0
  32. package/dist/internal/comment-watch/paths.js.map +1 -0
  33. package/dist/internal/comment-watch/platform.js +66 -0
  34. package/dist/internal/comment-watch/platform.js.map +1 -0
  35. package/dist/internal/comment-watch/protocol.js +124 -0
  36. package/dist/internal/comment-watch/protocol.js.map +1 -0
  37. package/dist/internal/comment-watch/recent.js +27 -0
  38. package/dist/internal/comment-watch/recent.js.map +1 -0
  39. package/dist/internal/comment-watch/replies.js +28 -0
  40. package/dist/internal/comment-watch/replies.js.map +1 -0
  41. package/dist/internal/comment-watch/service.js +174 -0
  42. package/dist/internal/comment-watch/service.js.map +1 -0
  43. package/dist/internal/comment-watch/settings.js +66 -0
  44. package/dist/internal/comment-watch/settings.js.map +1 -0
  45. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js +85 -0
  46. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js.map +1 -0
  47. package/dist/internal/comment-watch/source/github-pull-requests/impl.js +276 -0
  48. package/dist/internal/comment-watch/source/github-pull-requests/impl.js.map +1 -0
  49. package/dist/internal/comment-watch/source/github-pull-requests/queries.js +97 -0
  50. package/dist/internal/comment-watch/source/github-pull-requests/queries.js.map +1 -0
  51. package/dist/internal/comment-watch/source/google-doc/doc.js +57 -0
  52. package/dist/internal/comment-watch/source/google-doc/doc.js.map +1 -0
  53. package/dist/internal/comment-watch/source/google-doc/impl.js +190 -0
  54. package/dist/internal/comment-watch/source/google-doc/impl.js.map +1 -0
  55. package/dist/internal/comment-watch/source/http-api.js +74 -0
  56. package/dist/internal/comment-watch/source/http-api.js.map +1 -0
  57. package/dist/internal/comment-watch/source/interface.js +48 -0
  58. package/dist/internal/comment-watch/source/interface.js.map +1 -0
  59. package/dist/internal/comment-watch/source/sign-in.js +40 -0
  60. package/dist/internal/comment-watch/source/sign-in.js.map +1 -0
  61. package/dist/internal/comment-watch/source/sources.js +15 -0
  62. package/dist/internal/comment-watch/source/sources.js.map +1 -0
  63. package/dist/internal/comment-watch/store/impl.js +242 -0
  64. package/dist/internal/comment-watch/store/impl.js.map +1 -0
  65. package/dist/internal/comment-watch/store/interface.js +10 -0
  66. package/dist/internal/comment-watch/store/interface.js.map +1 -0
  67. package/dist/internal/comment-watch/t3.js +49 -0
  68. package/dist/internal/comment-watch/t3.js.map +1 -0
  69. package/dist/internal/comment-watch/watching.js +65 -0
  70. package/dist/internal/comment-watch/watching.js.map +1 -0
  71. package/dist/internal/comment-watch/workflow/comment-watch.js +19 -0
  72. package/dist/internal/comment-watch/workflow/comment-watch.js.map +1 -0
  73. package/dist/internal/comment-watch/workflow/deliver.js +104 -0
  74. package/dist/internal/comment-watch/workflow/deliver.js.map +1 -0
  75. package/dist/internal/comment-watch/workflow/find.js +67 -0
  76. package/dist/internal/comment-watch/workflow/find.js.map +1 -0
  77. package/dist/internal/comment-watch/workflow/post-once.js +66 -0
  78. package/dist/internal/comment-watch/workflow/post-once.js.map +1 -0
  79. package/dist/internal/comment-watch/workflow/post.js +40 -0
  80. package/dist/internal/comment-watch/workflow/post.js.map +1 -0
  81. package/dist/internal/config.js +131 -0
  82. package/dist/internal/config.js.map +1 -0
  83. package/dist/internal/control.js +113 -0
  84. package/dist/internal/control.js.map +1 -0
  85. package/dist/internal/daemon-control/impl.js +80 -0
  86. package/dist/internal/daemon-control/impl.js.map +1 -0
  87. package/dist/internal/daemon-control/interface.js +4 -0
  88. package/dist/internal/daemon-control/interface.js.map +1 -0
  89. package/dist/internal/folders.js +47 -0
  90. package/dist/internal/folders.js.map +1 -0
  91. package/dist/internal/local-skills.js +43 -0
  92. package/dist/internal/local-skills.js.map +1 -0
  93. package/dist/internal/path.js +36 -0
  94. package/dist/internal/path.js.map +1 -0
  95. package/dist/internal/server.js +80 -0
  96. package/dist/internal/server.js.map +1 -0
  97. package/dist/internal/skill-check.js +83 -0
  98. package/dist/internal/skill-check.js.map +1 -0
  99. package/dist/internal/skill-refinement/evals/cases.js +143 -0
  100. package/dist/internal/skill-refinement/evals/cases.js.map +1 -0
  101. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  102. package/dist/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  103. package/dist/internal/skill-refinement/feedback/import-legacy.js +13 -0
  104. package/dist/internal/skill-refinement/feedback/import-legacy.js.map +1 -0
  105. package/dist/internal/skill-refinement/feedback/intake.js +52 -0
  106. package/dist/internal/skill-refinement/feedback/intake.js.map +1 -0
  107. package/dist/internal/skill-refinement/feedback/managed-intake.js +19 -0
  108. package/dist/internal/skill-refinement/feedback/managed-intake.js.map +1 -0
  109. package/dist/internal/skill-refinement/feedback/outbox.js +44 -0
  110. package/dist/internal/skill-refinement/feedback/outbox.js.map +1 -0
  111. package/dist/internal/skill-refinement/jev/impl.js +63 -0
  112. package/dist/internal/skill-refinement/jev/impl.js.map +1 -0
  113. package/dist/internal/skill-refinement/jev/interface.js +6 -0
  114. package/dist/internal/skill-refinement/jev/interface.js.map +1 -0
  115. package/dist/internal/skill-refinement/managed-daemon.js +30 -0
  116. package/dist/internal/skill-refinement/managed-daemon.js.map +1 -0
  117. package/dist/internal/skill-refinement/managed-worker-credentials.js +60 -0
  118. package/dist/internal/skill-refinement/managed-worker-credentials.js.map +1 -0
  119. package/dist/internal/skill-refinement/managed-worker-files.js +25 -0
  120. package/dist/internal/skill-refinement/managed-worker-files.js.map +1 -0
  121. package/dist/internal/skill-refinement/managed-worker-loop.js +36 -0
  122. package/dist/internal/skill-refinement/managed-worker-loop.js.map +1 -0
  123. package/dist/internal/skill-refinement/organization-site.js +13 -0
  124. package/dist/internal/skill-refinement/organization-site.js.map +1 -0
  125. package/dist/internal/skill-refinement/paths.js +62 -0
  126. package/dist/internal/skill-refinement/paths.js.map +1 -0
  127. package/dist/internal/skill-refinement/platform.js +67 -0
  128. package/dist/internal/skill-refinement/platform.js.map +1 -0
  129. package/dist/internal/skill-refinement/service.js +365 -0
  130. package/dist/internal/skill-refinement/service.js.map +1 -0
  131. package/dist/internal/skill-refinement/skills/skill-text.js +219 -0
  132. package/dist/internal/skill-refinement/skills/skill-text.js.map +1 -0
  133. package/dist/internal/skill-refinement/workflow/retry.js +44 -0
  134. package/dist/internal/skill-refinement/workflow/retry.js.map +1 -0
  135. package/dist/internal/skill-refinement/workflow/skill-refinement.js +690 -0
  136. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +1 -0
  137. package/dist/internal/skill-refinement/writer/impl.js +2 -0
  138. package/dist/internal/skill-refinement/writer/impl.js.map +1 -0
  139. package/dist/internal/skill-refinement/writer/interface.js +2 -0
  140. package/dist/internal/skill-refinement/writer/interface.js.map +1 -0
  141. package/dist/internal/sync.js +182 -0
  142. package/dist/internal/sync.js.map +1 -0
  143. package/dist/internal/wire.js +31 -0
  144. package/dist/internal/wire.js.map +1 -0
  145. package/dist/internal/writer/claude.js +84 -0
  146. package/dist/internal/writer/claude.js.map +1 -0
  147. package/dist/internal/writer/codex.js +102 -0
  148. package/dist/internal/writer/codex.js.map +1 -0
  149. package/dist/internal/writer/interface.js +6 -0
  150. package/dist/internal/writer/interface.js.map +1 -0
  151. package/dist/internal/writer/live.js +13 -0
  152. package/dist/internal/writer/live.js.map +1 -0
  153. package/dist/internal/writer/reset.js +38 -0
  154. package/dist/internal/writer/reset.js.map +1 -0
  155. package/dist/internal/writer/selection.js +79 -0
  156. package/dist/internal/writer/selection.js.map +1 -0
  157. package/package.json +45 -11
  158. package/postinstall.cjs +663 -0
  159. package/src/daemons/skill-sync-daemon.ts +677 -0
  160. package/src/entrypoints/skill-sync.ts +12 -0
  161. package/src/index.ts +15 -0
  162. package/src/internal/agents/agent-tool.ts +149 -0
  163. package/src/internal/agents/claude.ts +442 -0
  164. package/src/internal/agents/codex.ts +288 -0
  165. package/src/internal/agents/command.ts +257 -0
  166. package/src/internal/agents/grok.ts +174 -0
  167. package/src/internal/agents/index.ts +74 -0
  168. package/src/internal/cli.ts +249 -0
  169. package/src/internal/comment-watch/held.ts +20 -0
  170. package/src/internal/comment-watch/key.ts +5 -0
  171. package/src/internal/comment-watch/message.ts +39 -0
  172. package/src/internal/comment-watch/paths.ts +17 -0
  173. package/src/internal/comment-watch/platform.ts +69 -0
  174. package/src/internal/comment-watch/protocol.ts +140 -0
  175. package/src/internal/comment-watch/recent.ts +26 -0
  176. package/src/internal/comment-watch/replies.ts +28 -0
  177. package/src/internal/comment-watch/service.ts +198 -0
  178. package/src/internal/comment-watch/settings.ts +82 -0
  179. package/src/internal/comment-watch/source/github-pull-requests/conversations.ts +111 -0
  180. package/src/internal/comment-watch/source/github-pull-requests/impl.ts +291 -0
  181. package/src/internal/comment-watch/source/github-pull-requests/queries.ts +113 -0
  182. package/src/internal/comment-watch/source/google-doc/doc.ts +76 -0
  183. package/src/internal/comment-watch/source/google-doc/impl.ts +198 -0
  184. package/src/internal/comment-watch/source/http-api.ts +93 -0
  185. package/src/internal/comment-watch/source/interface.ts +116 -0
  186. package/src/internal/comment-watch/source/sign-in.ts +45 -0
  187. package/src/internal/comment-watch/source/sources.ts +20 -0
  188. package/src/internal/comment-watch/store/impl.ts +268 -0
  189. package/src/internal/comment-watch/store/interface.ts +83 -0
  190. package/src/internal/comment-watch/t3.ts +68 -0
  191. package/src/internal/comment-watch/watching.ts +122 -0
  192. package/src/internal/comment-watch/workflow/comment-watch.ts +34 -0
  193. package/src/internal/comment-watch/workflow/deliver.ts +115 -0
  194. package/src/internal/comment-watch/workflow/find.ts +78 -0
  195. package/src/internal/comment-watch/workflow/post-once.ts +72 -0
  196. package/src/internal/comment-watch/workflow/post.ts +56 -0
  197. package/src/internal/config.ts +172 -0
  198. package/src/internal/control.ts +165 -0
  199. package/src/internal/daemon-control/impl.ts +94 -0
  200. package/src/internal/daemon-control/interface.ts +46 -0
  201. package/src/internal/folders.ts +50 -0
  202. package/src/internal/local-skills.ts +58 -0
  203. package/src/internal/path.ts +32 -0
  204. package/src/internal/server.ts +76 -0
  205. package/src/internal/skill-check.ts +97 -0
  206. package/src/internal/skill-refinement/evals/cases.ts +167 -0
  207. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  208. package/src/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  209. package/src/internal/skill-refinement/feedback/import-legacy.ts +16 -0
  210. package/src/internal/skill-refinement/feedback/intake.ts +66 -0
  211. package/src/internal/skill-refinement/feedback/managed-intake.ts +19 -0
  212. package/src/internal/skill-refinement/feedback/outbox.ts +50 -0
  213. package/src/internal/skill-refinement/jev/impl.ts +76 -0
  214. package/src/internal/skill-refinement/jev/interface.ts +56 -0
  215. package/src/internal/skill-refinement/managed-daemon.ts +38 -0
  216. package/src/internal/skill-refinement/managed-worker-credentials.ts +59 -0
  217. package/src/internal/skill-refinement/managed-worker-files.ts +24 -0
  218. package/src/internal/skill-refinement/managed-worker-loop.ts +46 -0
  219. package/src/internal/skill-refinement/organization-site.ts +15 -0
  220. package/src/internal/skill-refinement/paths.ts +87 -0
  221. package/src/internal/skill-refinement/platform.ts +71 -0
  222. package/src/internal/skill-refinement/service.ts +418 -0
  223. package/src/internal/skill-refinement/skills/skill-text.ts +292 -0
  224. package/src/internal/skill-refinement/workflow/retry.ts +61 -0
  225. package/src/internal/skill-refinement/workflow/skill-refinement.ts +777 -0
  226. package/src/internal/skill-refinement/writer/impl.ts +1 -0
  227. package/src/internal/skill-refinement/writer/interface.ts +1 -0
  228. package/src/internal/sync.ts +216 -0
  229. package/src/internal/wire.ts +439 -0
  230. package/src/internal/writer/claude.ts +98 -0
  231. package/src/internal/writer/codex.ts +93 -0
  232. package/src/internal/writer/interface.ts +48 -0
  233. package/src/internal/writer/live.ts +19 -0
  234. package/src/internal/writer/reset.ts +34 -0
  235. package/src/internal/writer/selection.ts +84 -0
  236. package/multi-call-binary +0 -4
@@ -0,0 +1,94 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { Effect, Layer, Option, Stream, pipe } from "effect";
3
+ import { daemonStatuses } from "jive-abstract-library";
4
+ import { name } from "../../../package.json";
5
+ import { DaemonFailed, requestEvents, type ControlEvent, type ControlRequest } from "../control";
6
+ import type { Replied } from "../comment-watch/service";
7
+ import type { Watching } from "../comment-watch/watching";
8
+ import type { ListedSkill } from "../wire";
9
+ import { DaemonControl, type AddedSkill, type DaemonError, type IDaemonControl } from "./interface";
10
+
11
+ class DaemonControlImpl implements IDaemonControl {
12
+ *login(openSignInPage: (url: string) => Effect.Effect<void>): Effect.fn.Return<string, DaemonError> {
13
+ const event = yield* finalEvent({ type: "login" }, (event) => event.type === "open" ? openSignInPage(event.url) : Effect.void);
14
+ if (event.type !== "signedIn") return yield* unexpected(event);
15
+ return event.machine;
16
+ }
17
+
18
+ *logout(): Effect.fn.Return<boolean, DaemonError> {
19
+ const event = yield* finalEvent({ type: "logout" });
20
+ if (event.type !== "signedOut") return yield* unexpected(event);
21
+ return event.revoked;
22
+ }
23
+
24
+ *listSyncedSkills(): Effect.fn.Return<ReadonlyArray<ListedSkill>, DaemonError> {
25
+ const event = yield* finalEvent({ type: "list" });
26
+ if (event.type !== "list") return yield* unexpected(event);
27
+ return event.skills;
28
+ }
29
+
30
+ *addSkill(skill: string): Effect.fn.Return<AddedSkill, DaemonError> {
31
+ const event = yield* finalEvent({ type: "add", skill });
32
+ if (event.type !== "added") return yield* unexpected(event);
33
+ return { added: event.added, folders: event.folders, syncingFolders: event.syncingFolders };
34
+ }
35
+
36
+ *addFeedback(item: { readonly slug: string; readonly text: string }): Effect.fn.Return<string, DaemonError> {
37
+ const event = yield* finalEvent({ type: "feedback", slug: item.slug, text: item.text });
38
+ if (event.type !== "feedbackAdded") return yield* unexpected(event);
39
+ return event.id;
40
+ }
41
+
42
+ *watching(): Effect.fn.Return<Watching, DaemonError> {
43
+ const event = yield* finalEvent({ type: "watching" });
44
+ if (event.type !== "watching") return yield* unexpected(event);
45
+ return event.watching;
46
+ }
47
+
48
+ *reply(words: { readonly key: string; readonly text: string }): Effect.fn.Return<Replied, DaemonError> {
49
+ const event = yield* finalEvent({ type: "reply", ...words });
50
+ if (event.type !== "replied") return yield* unexpected(event);
51
+ return event.replied;
52
+ }
53
+
54
+ *startDaemon(): Effect.fn.Return<void> {
55
+ const statuses = yield* pipe(daemonStatuses, Effect.catch(() => Effect.succeed([])));
56
+ const ours = statuses.filter((status) => status.registration.packageName === name && status.executableExists);
57
+ for (const { registration } of ours) {
58
+ const command: string[] = registration.kind === "launchd"
59
+ ? ["launchctl", "kickstart", "-k", `gui/${process.getuid?.() ?? 0}/${registration.unit}`]
60
+ : registration.kind === "systemd"
61
+ ? ["systemctl", "--user", "restart", registration.unit]
62
+ : ["schtasks", "/Run", "/TN", registration.unit];
63
+ const result = yield* Effect.sync(() => spawnSync(command[0]!, command.slice(1), { stdio: ["ignore", "ignore", "pipe"] }));
64
+ if (result.status !== 0) {
65
+ yield* Effect.logError(`Could not start ${registration.unit}: ${String(result.stderr ?? "").trim() || `exit ${result.status}`}`);
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ /** The event that ends the conversation, after handing each earlier one (only `open`, during login) to `onEvent`. */
72
+ function finalEvent(
73
+ message: ControlRequest,
74
+ onEvent: (event: ControlEvent) => Effect.Effect<void> = () => Effect.void,
75
+ ): Effect.Effect<ControlEvent, DaemonError> {
76
+ return pipe(
77
+ requestEvents(message),
78
+ Stream.tap(onEvent),
79
+ Stream.runLast,
80
+ Effect.flatMap(Option.match({
81
+ onNone: () => Effect.fail(new DaemonFailed({ message: "the daemon closed the connection without answering" })),
82
+ onSome: (event) => Effect.succeed(event),
83
+ })),
84
+ );
85
+ }
86
+
87
+ /** An `error` event is the daemon refusing the request; anything else is an answer to a different request. */
88
+ function unexpected(event: ControlEvent): Effect.Effect<never, DaemonFailed> {
89
+ return Effect.fail(new DaemonFailed({
90
+ message: event.type === "error" ? event.message : `unexpected answer from the daemon: ${JSON.stringify(event)}`,
91
+ }));
92
+ }
93
+
94
+ export const DaemonControlLive = Layer.succeed(DaemonControl, new DaemonControlImpl());
@@ -0,0 +1,46 @@
1
+ import { Context, type Effect } from "effect";
2
+ import type { DaemonFailed, DaemonNotRunning } from "../control";
3
+ import type { Replied } from "../comment-watch/service";
4
+ import type { Watching } from "../comment-watch/watching";
5
+ import type { ListedSkill } from "../wire";
6
+
7
+ export type DaemonError = DaemonNotRunning | DaemonFailed;
8
+
9
+ /** What `addSkill` did; see the `added` event in `control.ts`. */
10
+ export interface AddedSkill {
11
+ /** False when the skill was already on the synced list. */
12
+ readonly added: boolean;
13
+ /** This machine's folders that hold the skill. */
14
+ readonly folders: ReadonlyArray<string>;
15
+ /** Those of them ticked on the dashboard, which upload it. */
16
+ readonly syncingFolders: ReadonlyArray<string>;
17
+ }
18
+
19
+ /**
20
+ * What the CLI asks of the running daemon, which owns the sync token, so every request that needs the token goes
21
+ * through it. Every method fails with `DaemonNotRunning` when no daemon listens; none starts one by itself, so Tab
22
+ * completion can ask without waiting for a daemon to start.
23
+ */
24
+ export interface IDaemonControl {
25
+ /**
26
+ * Signs this machine in. `openSignInPage` is given the page where a passkey approves the sign-in, on this computer or
27
+ * any other, and the method returns the machine's name once the daemon has claimed its token.
28
+ */
29
+ login(openSignInPage: (url: string) => Effect.Effect<void>): Effect.fn.Return<string, DaemonError>;
30
+ /** Signs this machine out; returns whether the server revoked the token. */
31
+ logout(): Effect.fn.Return<boolean, DaemonError>;
32
+ /** The synced list, as the server holds it. */
33
+ listSyncedSkills(): Effect.fn.Return<ReadonlyArray<ListedSkill>, DaemonError>;
34
+ /** Puts a skill on this machine on the synced list, once the daemon has checked its files. */
35
+ addSkill(skill: string): Effect.fn.Return<AddedSkill, DaemonError>;
36
+ /** Hands one feedback item to this machine's skill refinement workflow; returns its id in the intake. */
37
+ addFeedback(item: { readonly slug: string; readonly text: string }): Effect.fn.Return<string, DaemonError>;
38
+ /** What the daemon is watching for comments now, as its own reads found it. */
39
+ watching(): Effect.fn.Return<Watching, DaemonError>;
40
+ /** Hands over an agent's words for a comment it was told of; says what became of them. */
41
+ reply(words: { readonly key: string; readonly text: string }): Effect.fn.Return<Replied, DaemonError>;
42
+ /** Starts this package's registered daemon through its service manager (launchd, systemd or Task Scheduler). */
43
+ startDaemon(): Effect.fn.Return<void>;
44
+ }
45
+
46
+ export class DaemonControl extends Context.Service<DaemonControl, IDaemonControl>()("DaemonControl") {}
@@ -0,0 +1,50 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { detectFolders } from "./agents";
4
+ import { hashBytes, listLocalFiles, type Config } from "./config";
5
+ import { fetchServer } from "./server";
6
+ import {
7
+ skillOf, type FileHash, type FolderPrefs, type FoldersRequest, type FoldersResponse, type LocalSkill,
8
+ } from "./wire";
9
+
10
+ /**
11
+ * What this machine tells the service about its folders, and what it hears back.
12
+ *
13
+ * The daemon and the CLI both register, so this lives in one place: they must describe a folder the same
14
+ * way, or the dashboard would show whichever of them spoke last.
15
+ */
16
+
17
+ /**
18
+ * The skills on disk in one folder, with each file's hash. Hashing every file on each check is cheap at
19
+ * skills' size, and it is what lets the dashboard show whether this folder's copy is the synced one.
20
+ */
21
+ export function localSkills(folder: string, config: Config): LocalSkill[] {
22
+ const byName = new Map<string, FileHash[]>();
23
+ for (const path of listLocalFiles(folder, config.exclude)) {
24
+ const name = skillOf(path);
25
+ let hash: string;
26
+ try {
27
+ hash = hashBytes(readFileSync(join(folder, path)));
28
+ } catch {
29
+ continue; // Deleted between listing and reading; the next check reports the folder as it is.
30
+ }
31
+ byName.set(name, [...(byName.get(name) ?? []), { path, hash }]);
32
+ }
33
+ return [...byName].map(([name, files]) => ({ name, files }));
34
+ }
35
+
36
+ /** Everything registration sends, so a caller can tell when it has changed and is worth re-sending. */
37
+ export function describe(config: Config): FoldersRequest {
38
+ return { folders: detectFolders().map((path) => ({ path, skills: localSkills(path, config) })) };
39
+ }
40
+
41
+ /** Registers this machine's folders and skills; returns the folders to sync and the skills in each. */
42
+ export async function register(config: Config, request: FoldersRequest): Promise<ReadonlyArray<FolderPrefs>> {
43
+ const response = await fetchServer(config, "/folders", {
44
+ method: "POST",
45
+ headers: { "content-type": "application/json" },
46
+ body: JSON.stringify(request),
47
+ });
48
+ if (!response.ok) throw new Error(`POST /folders: ${response.status} ${await response.text()}`);
49
+ return (await response.json() as FoldersResponse).folders;
50
+ }
@@ -0,0 +1,58 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Option } from "effect";
4
+ import { isLock } from "./config";
5
+ import { checkSkillToAdd, readFrontmatter } from "./skill-check";
6
+
7
+ /** Skills as this machine's detected skills folders hold them, for the CLI's `show` and `add`. */
8
+
9
+ /** One folder's copy of a skill, with the description its `SKILL.md` frontmatter gives. */
10
+ export interface SkillCopy {
11
+ readonly path: string;
12
+ readonly description: Option.Option<string>;
13
+ }
14
+
15
+ /** Every copy of `skill` in `folders`, in the order of `folders`. */
16
+ export function skillCopies(input: { readonly skill: string; readonly folders: ReadonlyArray<string> }): ReadonlyArray<SkillCopy> {
17
+ return input.folders
18
+ .map((folder) => join(folder, input.skill))
19
+ .filter((path) => existsSync(path))
20
+ .map((path) => ({ path, description: readDescription(join(path, "SKILL.md")) }));
21
+ }
22
+
23
+ /**
24
+ * What `skill-sync show` prints: each description above the paths of the copies that have it. Copies agree once
25
+ * synced, so this is usually one description; copies that differ are shown apart rather than one hiding another.
26
+ */
27
+ export function formatSkillCopies(copies: ReadonlyArray<SkillCopy>): string {
28
+ const byDescription = Map.groupBy(copies, (copy) => Option.getOrElse(copy.description, () => "(its SKILL.md has no description)"));
29
+ return [...byDescription]
30
+ .map(([description, group]) => [description, ...group.map((copy) => ` ${copy.path}`)].join("\n"))
31
+ .join("\n\n");
32
+ }
33
+
34
+ /**
35
+ * The skills in `folders` that are not on the synced list and that `skill-sync add` would accept: the same check
36
+ * the daemon runs before adding (`checkSkillToAdd`), so Tab offers nothing the daemon would refuse.
37
+ */
38
+ export function addableSkills(input: {
39
+ readonly folders: ReadonlyArray<string>;
40
+ readonly exclude: ReadonlyArray<string>;
41
+ readonly synced: ReadonlyArray<string>;
42
+ }): ReadonlyArray<string> {
43
+ const { folders, exclude, synced } = input;
44
+ const names = new Set(folders.flatMap((folder) => entries(folder).filter((entry) => !entry.startsWith(".") && !isLock(entry))));
45
+ return [...names]
46
+ .filter((skill) => !synced.includes(skill) && checkSkillToAdd({ skill, folders, exclude }).ok)
47
+ .sort();
48
+ }
49
+
50
+ function readDescription(skillFile: string): Option.Option<string> {
51
+ if (!existsSync(skillFile)) return Option.none();
52
+ const description = readFrontmatter(readFileSync(skillFile, "utf8"))?.get("description");
53
+ return description === undefined || description === "" ? Option.none() : Option.some(description);
54
+ }
55
+
56
+ function entries(folder: string): ReadonlyArray<string> {
57
+ return existsSync(folder) ? readdirSync(folder) : [];
58
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Validation for the one piece of untrusted input that becomes a filesystem path.
3
+ *
4
+ * Shared by the Worker and the daemon on purpose, and deliberately free of any Node import so the Worker
5
+ * can bundle it. Both ends check: the server so one compromised client cannot poison what every machine
6
+ * pulls, and the daemon because a server it does not control is not a thing to take paths from either.
7
+ *
8
+ * Without this, a pushed path of `../../.ssh/authorized_keys` is joined to the skills directory and
9
+ * written wherever the daemon's user can write.
10
+ */
11
+
12
+ /** Long enough for any real nesting, short enough that nothing can be used to exhaust anything. */
13
+ const MAX_LENGTH = 512;
14
+
15
+ export function invalidPathReason(path: string): string | undefined {
16
+ if (path.length === 0 || path.length > MAX_LENGTH) return "path is empty or too long";
17
+ if (path.includes("\0")) return "path contains a null byte";
18
+ if (path.includes("\\")) return "path must use forward slashes";
19
+ if (path.startsWith("/")) return "path must be relative";
20
+ // A Windows drive letter is absolute on the machine that matters even though it has no leading slash.
21
+ if (/^[A-Za-z]:/.test(path)) return "path must be relative";
22
+
23
+ for (const segment of path.split("/")) {
24
+ if (segment === "") return "path has an empty segment";
25
+ if (segment === "." || segment === "..") return "path must not contain . or .. segments";
26
+ }
27
+ return undefined;
28
+ }
29
+
30
+ export function isValidPath(path: string): boolean {
31
+ return invalidPathReason(path) === undefined;
32
+ }
@@ -0,0 +1,76 @@
1
+ import type { Config } from "./config";
2
+ import { MACHINE_HEADER, MACHINE_MISMATCH_STATUS, type MachineMismatch, type SignInClaim, type SignInRequestCreated } from "./wire";
3
+
4
+ /**
5
+ * Requests to the skill-sync service, signed with this machine's token.
6
+ *
7
+ * Every request goes through `fetchServer`, so a token the server no longer accepts, or one issued to another
8
+ * machine, is noticed the same way whichever request hits it first.
9
+ */
10
+
11
+ /** The server answered 401: the token was revoked or is unknown, so no retry with it can succeed. */
12
+ export class TokenRejected extends Error {
13
+ constructor(message: string, readonly token: string) {
14
+ super(message);
15
+ }
16
+ }
17
+
18
+ /**
19
+ * The server answered that the token belongs to `tokenMachine`, not to the machine this one is configured as:
20
+ * most often a token file copied from another computer. No request with it can succeed, and the token is
21
+ * still that other machine's, so it must not be revoked from here.
22
+ */
23
+ export class TokenOfAnotherMachine extends Error {
24
+ constructor(readonly configuredMachine: string, readonly tokenMachine: string, readonly token: string) {
25
+ super(`this machine is configured as "${configuredMachine}" but its token belongs to "${tokenMachine}"`);
26
+ }
27
+ }
28
+
29
+ export function authHeaders(config: Config, extra: Record<string, string>): Record<string, string> {
30
+ return { authorization: `Bearer ${config.token}`, [MACHINE_HEADER]: config.machine, ...extra };
31
+ }
32
+
33
+ /**
34
+ * Sends one request to the server with the token. Throws `TokenRejected` on 401 and `TokenOfAnotherMachine` on
35
+ * the service's machine mismatch; every other status is returned for the caller to judge, since some (a 409
36
+ * from `PUT /files`) are answers rather than failures.
37
+ */
38
+ export async function fetchServer(config: Config, path: string, init: RequestInit = {}): Promise<Response> {
39
+ const response = await fetch(`${config.endpoint}${path}`, {
40
+ ...init,
41
+ headers: authHeaders(config, (init.headers ?? {}) as Record<string, string>),
42
+ });
43
+ if (response.status === 401) {
44
+ throw new TokenRejected(`${init.method ?? "GET"} ${path}: the server rejected this machine's token`, config.token);
45
+ }
46
+ if (response.status === MACHINE_MISMATCH_STATUS) {
47
+ const body = await response.clone().json().catch(() => undefined) as Partial<MachineMismatch> | undefined;
48
+ if (typeof body?.tokenMachine === "string") throw new TokenOfAnotherMachine(config.machine, body.tokenMachine, config.token);
49
+ }
50
+ return response;
51
+ }
52
+
53
+ /**
54
+ * Opens a request to sign `machine` in. Sent without a token: the machine has none yet. See `SignInRequestCreated`
55
+ * for what comes back and why the claim secret never leaves this process.
56
+ */
57
+ export async function openSignInRequest(input: { readonly endpoint: string; readonly machine: string }): Promise<SignInRequestCreated> {
58
+ const response = await fetch(`${input.endpoint}/cli/sign-in-requests`, {
59
+ method: "POST",
60
+ headers: { "content-type": "application/json" },
61
+ body: JSON.stringify({ machine: input.machine }),
62
+ });
63
+ if (!response.ok) throw new Error(`POST /cli/sign-in-requests: ${response.status} ${await response.text()}`);
64
+ return await response.json() as SignInRequestCreated;
65
+ }
66
+
67
+ /** Asks whether the request was approved; the answer carries the token once it was. */
68
+ export async function claimSignInRequest(input: { readonly endpoint: string; readonly claimSecret: string }): Promise<SignInClaim> {
69
+ const response = await fetch(`${input.endpoint}/cli/sign-in-requests/claim`, {
70
+ method: "POST",
71
+ headers: { "content-type": "application/json" },
72
+ body: JSON.stringify({ claimSecret: input.claimSecret }),
73
+ });
74
+ if (!response.ok) throw new Error(`POST /cli/sign-in-requests/claim: ${response.status} ${await response.text()}`);
75
+ return await response.json() as SignInClaim;
76
+ }
@@ -0,0 +1,97 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isSkillName } from "./wire";
4
+
5
+ /**
6
+ * Whether a skill on this machine may go on the synced list, checked before `skill-sync add` asks the
7
+ * server to add it.
8
+ *
9
+ * The synced list is for skills meant for every project. A skill made for one project lives in that
10
+ * project (its `.claude/skills`, `.agents/skills` or `.grok/skills`), which is never one of the folders
11
+ * skill-sync detects, so a skill is accepted only from a detected folder. That is the one sign of a
12
+ * project-specific skill that can be read from disk; a skill written into a home folder but about one
13
+ * project is not caught here.
14
+ */
15
+ export type SkillCheck =
16
+ | { readonly ok: true; readonly folders: ReadonlyArray<string> }
17
+ | { readonly ok: false; readonly reason: string };
18
+
19
+ export function checkSkillToAdd(input: {
20
+ readonly skill: string;
21
+ /** The skills folders skill-sync detects on this machine (`detectFolders`). */
22
+ readonly folders: ReadonlyArray<string>;
23
+ /** Top-level names skill-sync never syncs (`Settings.exclude`). */
24
+ readonly exclude: ReadonlyArray<string>;
25
+ }): SkillCheck {
26
+ const { skill, folders, exclude } = input;
27
+ if (!isSkillName(skill)) {
28
+ return { ok: false, reason: `"${skill}" is not a skill name: lowercase letters and digits in hyphen-joined words, at most 64 characters` };
29
+ }
30
+ if (exclude.includes(skill)) {
31
+ return { ok: false, reason: `"${skill}" is excluded from syncing in ~/.jive/skill-sync.json` };
32
+ }
33
+ const holding = folders.filter((folder) => isDirectory(join(folder, skill)));
34
+ if (holding.length === 0) {
35
+ return {
36
+ ok: false,
37
+ reason: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}. `
38
+ + "Only skills meant for every project sync: write the skill into one of those folders. A skill inside a "
39
+ + "project's own skills folder is specific to that project and stays there.",
40
+ };
41
+ }
42
+ for (const folder of holding) {
43
+ const problem = frontmatterProblem(skill, join(folder, skill, "SKILL.md"));
44
+ if (problem !== undefined) return { ok: false, reason: problem };
45
+ }
46
+ return { ok: true, folders: holding };
47
+ }
48
+
49
+ /** Why a skill's `SKILL.md` would not load as that skill, or undefined when it would. */
50
+ function frontmatterProblem(skill: string, path: string): string | undefined {
51
+ if (!existsSync(path)) return `${path} does not exist; every skill needs a SKILL.md`;
52
+ const fields = readFrontmatter(readFileSync(path, "utf8"));
53
+ if (fields === undefined) return `${path} does not start with a frontmatter block between --- lines`;
54
+ const name = fields.get("name");
55
+ if (name === undefined || name === "") return `${path}'s frontmatter has no name`;
56
+ if (name !== skill) return `${path}'s frontmatter name is "${name}", but its folder is "${skill}"; they must match`;
57
+ if ((fields.get("description") ?? "") === "") return `${path}'s frontmatter has no description, which is how agents decide to load it`;
58
+ return undefined;
59
+ }
60
+
61
+ /**
62
+ * The top-level keys of a `SKILL.md`'s frontmatter, with their values as text. Covers what skills use: a
63
+ * plain or quoted value on the key's line, or a block (`>` or `|`) on the indented lines after it.
64
+ */
65
+ export function readFrontmatter(text: string): Map<string, string> | undefined {
66
+ const lines = text.replace(/^/, "").split(/\r?\n/);
67
+ if (lines[0]?.trim() !== "---") return undefined;
68
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
69
+ if (end === -1) return undefined;
70
+ const fields = new Map<string, string>();
71
+ let blockKey: string | undefined;
72
+ for (const line of lines.slice(1, end)) {
73
+ const field = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
74
+ if (field !== null) {
75
+ const key = field[1]!;
76
+ const raw = field[2]!;
77
+ blockKey = /^[>|][+-]?$/.test(raw.trim()) ? key : undefined;
78
+ fields.set(key, blockKey === undefined ? unquote(raw.trim()) : "");
79
+ } else if (blockKey !== undefined && /^\s+\S/.test(line)) {
80
+ fields.set(blockKey, `${fields.get(blockKey)} ${line.trim()}`.trim());
81
+ }
82
+ }
83
+ return fields;
84
+ }
85
+
86
+ function unquote(value: string): string {
87
+ const quoted = /^(["'])(.*)\1$/.exec(value);
88
+ return quoted === null ? value : quoted[2]!;
89
+ }
90
+
91
+ function isDirectory(path: string): boolean {
92
+ try {
93
+ return statSync(path).isDirectory();
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * THE A/B EXAMPLES: replies and actions Alex objected to (or labelled good), kept in `agentic-collaboration/evals/cases`.
3
+ * Each is replayed under every skill version a run tests: a writer writes the reply or action under that version, and Jev
4
+ * judges it against what the case had to convey and what went wrong (`agentic-collaboration` section 1, Test before
5
+ * installing).
6
+ */
7
+ import { Data, Effect, Schema } from 'effect';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ export const EvalCase = Schema.Struct({
12
+ id: Schema.String,
13
+ kind: Schema.optionalKey(Schema.Literals(['good', 'action'])),
14
+ his_question: Schema.String,
15
+ original_reply: Schema.String,
16
+ his_reaction: Schema.String,
17
+ intended: Schema.optionalKey(Schema.Struct({ facts: Schema.Array(Schema.String), he_must_do: Schema.String, intended_meaning: Schema.String })),
18
+ action: Schema.optionalKey(Schema.Struct({ state_before: Schema.Array(Schema.String), wanted: Schema.String, went_wrong: Schema.String })),
19
+ });
20
+ export type EvalCase = typeof EvalCase.Type;
21
+
22
+ export class CasesError extends Data.TaggedError('CasesError')<{ readonly reason: string }> {}
23
+
24
+ const decodeCase = Schema.decodeUnknownEffect(Schema.fromJsonString(EvalCase));
25
+
26
+ /** Every case that can be replayed: a reply case with its intended meaning, or an action case with its state. */
27
+ export const readCases = (folder: string): Effect.Effect<ReadonlyArray<EvalCase>, CasesError> => Effect.gen(function* () {
28
+ const files = yield* Effect.try({ try: () => fs.readdirSync(folder).filter((f) => f.endsWith('.json')).sort(), catch: (e) => new CasesError({ reason: `the cases could not be listed: ${String(e)}` }) });
29
+ const out: EvalCase[] = [];
30
+ for (const f of files) {
31
+ const text = yield* Effect.try({ try: () => fs.readFileSync(path.join(folder, f), 'utf8'), catch: (e) => new CasesError({ reason: `${f} could not be read: ${String(e)}` }) });
32
+ const c = yield* Effect.mapError(decodeCase(text), (e) => new CasesError({ reason: `${f} is not a case: ${e.message}` }));
33
+ if (replayable(c)) out.push(c);
34
+ }
35
+ return out;
36
+ });
37
+
38
+ export const replayable = (c: EvalCase): boolean => (c.kind === 'action' ? c.action !== undefined : c.intended !== undefined);
39
+
40
+ /** The next free case file name, `case-NN.json`. Pure. */
41
+ export const nextCaseFile = (existing: ReadonlyArray<string>): string => {
42
+ const numbers = existing.flatMap((f) => { const m = /^case-(\d+)\.json$/.exec(f); return m === null ? [] : [Number(m[1])]; });
43
+ return `case-${String(Math.max(0, ...numbers) + 1).padStart(2, '0')}.json`;
44
+ };
45
+
46
+ /** A case in a few lines, as Jev reads it when choosing which examples a rule governs. Pure. */
47
+ export const caseSummary = (c: EvalCase): string => [
48
+ `His message: ${c.his_question.slice(0, 500)}`,
49
+ `His reaction: ${c.his_reaction.slice(0, 400)}`,
50
+ c.action !== undefined ? `What went wrong: ${c.action.went_wrong.slice(0, 400)}` : `What the reply had to convey: ${c.intended?.intended_meaning.slice(0, 400) ?? ''}`,
51
+ ].join('\n');
52
+
53
+ /**
54
+ * What a writer is asked, under one skill version, for one case: the reply, or for an action case the changes it makes
55
+ * next and the reply. The same words as the evals' first runner (`evals/run.ts`), so results compare. Pure.
56
+ */
57
+ export const writerPrompt = (c: EvalCase): string => (c.kind === 'action' && c.action !== undefined
58
+ ? `Alex's latest message:\n${c.his_question}\n\nThe state of the work now (facts):\n- ${c.action.state_before.join('\n- ')}\n\n`
59
+ + 'You have no tools in this exercise. Write PLAN: the concrete changes you make next, exactly as you would make them '
60
+ + '(what is added, removed or moved, and what he will see afterwards), then REPLY: the exact text you send Alex.'
61
+ : `Alex's latest message:\n${c.his_question}\n\nWhat you know now from this turn's tool results (facts, not wording):\n- ${c.intended?.facts.join('\n- ') ?? ''}\n`
62
+ + `What he has to do or decide: ${c.intended?.he_must_do ?? ''}\n\nWrite the exact reply you send Alex now. Output only the reply text.`);
63
+
64
+ /** The rules a writer writes under: one skill version's text. Pure. */
65
+ export const writerSystem = (skill: string, text: string): string =>
66
+ `You are an agent working for Alex. These are your rules, loaded at the start of this session:\n\n# Skill: ${skill}\n\n${text}`;
67
+
68
+ /**
69
+ * WHO JUDGES A CASE, BY ITS KIND. A reply case (how a reply reads) goes to Jev, held to the Opus judge's agreement with
70
+ * Alex by calibration. An action case (what got built or done) goes to the Opus judge: on 68 action cases (2026-11-16)
71
+ * Jev failed every plan, the ones exactly as he wanted included, and no cut on its probabilities held up live. Alex,
72
+ * choosing this: "Sure. I mean that can be encoded in the workflow logic right?". Pure.
73
+ */
74
+ export const judgeOf = (c: EvalCase): 'opus' | 'jev' => (c.kind === 'action' ? 'opus' : 'jev');
75
+
76
+ /** Who Jev reads a reply as. */
77
+ export const JUDGE_ALEX = 'Alex is an engineer who reads replies on his phone, cannot scroll back, and objects to any reply that makes him work to understand it, guesses at what he meant, or adds what he did not ask for.';
78
+
79
+ /** What Jev is told about one written reply: what it had to convey and the reply, as the Opus judge was told. Pure. */
80
+ export const judgeState = (c: EvalCase, reply: string) => ({
81
+ alex: JUDGE_ALEX,
82
+ his_message: c.his_question,
83
+ what_the_reply_had_to_convey: c.intended?.intended_meaning ?? '',
84
+ facts: c.intended?.facts ?? [],
85
+ what_he_had_to_do: c.intended?.he_must_do ?? '',
86
+ reply,
87
+ });
88
+
89
+ /** His own terms, which a reply may use unexplained (the evals' first judge kept the same list). */
90
+ const ALEX_TERMS = '"Skill maintenance thread", "command thread", "control thread", "Blocked on you", "skill", "phase", "workflow"';
91
+
92
+ /** One yes-or-no criterion of the judge, and whether yes is what a passing reply has. */
93
+ interface Criterion { readonly instructions: string; readonly passesWhen: 'yes' | 'no' }
94
+
95
+ /**
96
+ * JEV'S CRITERIA FOR A REPLY: the Opus judge's rubric, one Jev question each, so a reply passes on the same checks it was
97
+ * calibrated on (every reply he objected to fails, the one he labelled good passes), read as a busy reader with no other
98
+ * context would read it.
99
+ */
100
+ export const REPLY_CRITERIA: Readonly<Record<string, Criterion>> = {
101
+ meaning_match: { passesWhen: 'yes', instructions: 'Reading only his message and this reply, once, as a busy person: would he understand exactly what the reply had to convey (in the state), with the facts it lists?' },
102
+ answer_first: { passesWhen: 'yes', instructions: 'Does the first sentence answer what he asked, or lead with what he must know?' },
103
+ needs_history: { passesWhen: 'no', instructions: 'Does the answer or an action depend on earlier messages he would have to look up ("the plan", "that thread", "as I said")?' },
104
+ undefined_labels: { passesWhen: 'no', instructions: `Does it use internal or coined labels (thread names, step names, project jargon) he did not use and it does not explain? Standard engineering terms do not count, and neither do his own terms: ${ALEX_TERMS}.` },
105
+ misleading_ambiguity: { passesWhen: 'no', instructions: 'Does a sentence about the answer, or about what he must do, have another plausible reading?' },
106
+ too_long: { passesWhen: 'no', instructions: 'Is it clearly longer than what he asked needs? A report he asked for may be long.' },
107
+ follow_up_needed: { passesWhen: 'no', instructions: 'Would he need to ask a follow-up question to understand it or act on it?' },
108
+ };
109
+
110
+ /**
111
+ * How strictly each criterion is judged. Measured on the 40 original replies the Opus judge graded (2026-11-16): the bare
112
+ * questions agreed with Alex on 34 and 35 of 40, these with this focus on 37, 37 and 36; the Opus judge on 35.
113
+ */
114
+ export const JUDGE_FOCUS = 'Judge strictly, as Alex would: when in doubt, the reply has the problem.';
115
+
116
+ /** Jev's questions for a reply case. Pure. */
117
+ export const judgeQuestions = () => Object.fromEntries(Object.entries(REPLY_CRITERIA).map(([k, v]) => [k, { type: 'noul' as const, instructions: { question: v.instructions, focus: JUDGE_FOCUS } }]));
118
+
119
+ /** A reply Jev judged: it passes when every criterion is on its passing side; its score is how far, for ranking. Pure. */
120
+ export const verdictOf = (answers: Readonly<Record<string, number>>): { readonly pass: boolean; readonly score: number } => {
121
+ let pass = true;
122
+ let score = 1;
123
+ for (const [k, v] of Object.entries(REPLY_CRITERIA)) {
124
+ const yes = answers[k] ?? 0;
125
+ const good = v.passesWhen === 'yes' ? yes : 1 - yes;
126
+ if (good < 0.5) pass = false;
127
+ score *= good;
128
+ }
129
+ return { pass, score };
130
+ };
131
+
132
+ /** The Opus judge's verdict on an action case, as its prompt asks for it. */
133
+ export const ActionVerdict = Schema.Struct({
134
+ does_what_he_wanted: Schema.Boolean,
135
+ adds_unasked: Schema.Boolean,
136
+ keeps_what_he_rejected: Schema.Boolean,
137
+ unstated_guess: Schema.Boolean,
138
+ why: Schema.String,
139
+ });
140
+ export type ActionVerdict = typeof ActionVerdict.Type;
141
+
142
+ /** Whether the Opus judge's verdict passes the plan; the evals' first runner passed it on the same four. Pure. */
143
+ export const actionPasses = (v: ActionVerdict): boolean => v.does_what_he_wanted && !v.adds_unasked && !v.keeps_what_he_rejected && !v.unstated_guess;
144
+
145
+ /**
146
+ * What the Opus judge is asked about one plan and reply: the evals' first runner's action judge (`evals/run.ts`), with one
147
+ * exclusion added to "adds_unasked": keeping the work's docs accurate and recording his decision. The skills require both
148
+ * ("update what describes it", "a direction he gives is written to the design doc or owning skill that turn"), and on
149
+ * 2026-11-16 11 of the 12 failing replies to three runs' own cases failed on "adds_unasked" alone, most for a README,
150
+ * design-doc or decision-record edit (others for deleting an old copy, which still counts). Calibration holds it to
151
+ * failing every action original the original prompt failed. Pure.
152
+ */
153
+ export const actionJudgePrompt = (c: EvalCase, output: string): string =>
154
+ 'Grade what an agent decided to do for Alex. You don\'t know who wrote it or under which rules. '
155
+ + 'The agent did not see his later reaction; you do, so you know what he wanted.\n\n'
156
+ + `The state before acting:\n- ${c.action?.state_before.join('\n- ') ?? ''}\n\nHis message:\n${c.his_question}\n\n`
157
+ + `What he wanted (from his later reaction): ${c.action?.wanted ?? ''}\nWhat a past agent got wrong here: ${c.action?.went_wrong ?? ''}\n\n`
158
+ + `The agent's plan and reply:\n${output}\n\n`
159
+ + 'Return only JSON: {"does_what_he_wanted": the result he would see is what he wanted, '
160
+ + '"adds_unasked": it builds, adds or rearranges something he would see that he didn\'t ask for; moving existing content to where the structure he asked for puts it, '
161
+ + 'tests or checks that guard what he asked for, and keeping the docs that describe the work accurate (its README or design doc, his decision recorded where the project keeps its decisions) don\'t count, '
162
+ + '"keeps_what_he_rejected": what he would see still contains something he said he doesn\'t want, '
163
+ + '"unstated_guess": where his message leaves the result open, it builds its own guess without stating the concrete result in the reply, '
164
+ + '"why": "one sentence"}';
165
+
166
+ /** The judge's version: everything a verdict depends on but the models. A change recalibrates Jev and requeues every item. */
167
+ export const judgeVersion = (): string => JSON.stringify({ REPLY_CRITERIA, JUDGE_FOCUS, JUDGE_ALEX, action: actionJudgePrompt({ id: '', his_question: '', original_reply: '', his_reaction: '', kind: 'action', action: { state_before: [], wanted: '', went_wrong: '' } }, '') });