@moo.md/hum 0.0.0-stage → 0.0.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 (150) hide show
  1. package/defaults/hum.json +321 -0
  2. package/defaults/kinds/check.json +183 -0
  3. package/defaults/kinds/docs.json +151 -0
  4. package/defaults/kinds/feature.json +202 -0
  5. package/defaults/kinds/fix.json +183 -0
  6. package/defaults/kinds/hotfix.json +164 -0
  7. package/defaults/roles/build.md +3 -0
  8. package/defaults/roles/fix.md +1 -0
  9. package/defaults/roles/plan.md +3 -0
  10. package/defaults/roles/review.md +3 -0
  11. package/evals/alignment/RESULTS.md +8 -0
  12. package/evals/alignment/cases.jsonl +128 -0
  13. package/evals/alignment/sample.jsonl +20 -0
  14. package/evals/kind/RESULTS.md +5 -0
  15. package/evals/kind/cases.jsonl +24 -0
  16. package/evals/plan-outcome/RESULTS.md +4 -0
  17. package/evals/plan-outcome/cases.jsonl +12 -0
  18. package/evals/repeat-pair/RESULTS.md +4 -0
  19. package/evals/repeat-pair/cases.jsonl +51 -0
  20. package/evals/reply-option/RESULTS.md +3 -0
  21. package/evals/reply-option/cases.jsonl +45 -0
  22. package/evals/review-verdict/RESULTS.md +4 -0
  23. package/evals/review-verdict/cases.jsonl +12 -0
  24. package/package.json +88 -4
  25. package/schema/hum.schema.json +1355 -0
  26. package/scripts/eval.ts +244 -0
  27. package/src/adapter-api.ts +134 -0
  28. package/src/adapters/admit.ts +111 -0
  29. package/src/adapters/argument.ts +11 -0
  30. package/src/adapters/claim.ts +93 -0
  31. package/src/adapters/claude-bg.ts +375 -0
  32. package/src/adapters/claude-p.ts +593 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +155 -0
  36. package/src/adapters/github.ts +457 -0
  37. package/src/adapters/guard.ts +152 -0
  38. package/src/adapters/history.ts +215 -0
  39. package/src/adapters/item-file.ts +102 -0
  40. package/src/adapters/limit.ts +67 -0
  41. package/src/adapters/markdown.ts +365 -0
  42. package/src/adapters/marked.ts +119 -0
  43. package/src/adapters/model-call.ts +75 -0
  44. package/src/adapters/once.ts +45 -0
  45. package/src/adapters/owner-commit.ts +60 -0
  46. package/src/adapters/pull-requests.ts +253 -0
  47. package/src/adapters/registry.ts +156 -0
  48. package/src/adapters/roundup.ts +291 -0
  49. package/src/adapters/serial.ts +22 -0
  50. package/src/adapters/transcript.ts +99 -0
  51. package/src/cli/commands.ts +46 -0
  52. package/src/cli/main.ts +8 -0
  53. package/src/cli/ops.ts +224 -0
  54. package/src/cli/service.ts +156 -0
  55. package/src/cli/setup.ts +141 -0
  56. package/src/cli/shared-watch.ts +127 -0
  57. package/src/config/change.ts +54 -0
  58. package/src/config/checks.ts +217 -0
  59. package/src/config/git-ref-name.d.ts +3 -0
  60. package/src/config/hash.ts +6 -0
  61. package/src/config/json.ts +6 -0
  62. package/src/config/load.ts +88 -0
  63. package/src/config/machine.ts +20 -0
  64. package/src/config/migrate.ts +61 -0
  65. package/src/config/refusal.ts +58 -0
  66. package/src/config/schema.ts +465 -0
  67. package/src/config/settings.ts +6 -0
  68. package/src/config/state-map.ts +76 -0
  69. package/src/decide/alignment.ts +79 -0
  70. package/src/decide/answer.ts +131 -0
  71. package/src/decide/kind.ts +39 -0
  72. package/src/decide/labels.ts +137 -0
  73. package/src/decide/merge.ts +102 -0
  74. package/src/decide/prose.ts +109 -0
  75. package/src/decide/question.ts +159 -0
  76. package/src/decide/review.ts +10 -0
  77. package/src/decide/risk.ts +216 -0
  78. package/src/decide/taste.ts +37 -0
  79. package/src/exec.ts +80 -0
  80. package/src/index.ts +200 -0
  81. package/src/loop/breaks.ts +8 -0
  82. package/src/loop/check-item.ts +76 -0
  83. package/src/loop/ci.ts +8 -0
  84. package/src/loop/github.ts +81 -0
  85. package/src/loop/groups.ts +108 -0
  86. package/src/loop/memory.ts +70 -0
  87. package/src/loop/notes.ts +76 -0
  88. package/src/loop/pair.ts +39 -0
  89. package/src/loop/pass.ts +99 -0
  90. package/src/loop/proof.ts +85 -0
  91. package/src/loop/prove-item.ts +33 -0
  92. package/src/loop/records.ts +75 -0
  93. package/src/loop/signals.ts +130 -0
  94. package/src/measure/inputs.ts +28 -0
  95. package/src/measure/measure.ts +68 -0
  96. package/src/service/cards.ts +24 -0
  97. package/src/service/ci-tick.ts +28 -0
  98. package/src/service/launchd.ts +16 -0
  99. package/src/service/supervise.ts +145 -0
  100. package/src/service/systemd.ts +44 -0
  101. package/src/service/token.ts +21 -0
  102. package/src/service/unit.ts +29 -0
  103. package/src/service/wake.ts +30 -0
  104. package/src/service/workflows.ts +97 -0
  105. package/src/setup/propose.ts +120 -0
  106. package/src/setup/prove.ts +216 -0
  107. package/src/setup/scan.ts +186 -0
  108. package/src/setup/scratch.ts +81 -0
  109. package/src/setup/shipped.ts +15 -0
  110. package/src/setup/tables.ts +101 -0
  111. package/src/setup/waits.ts +58 -0
  112. package/src/setup/write.ts +161 -0
  113. package/src/slots/env.ts +42 -0
  114. package/src/slots/pool.ts +329 -0
  115. package/src/slots/scan.ts +26 -0
  116. package/src/slots/worktree.ts +17 -0
  117. package/src/state/events.ts +52 -0
  118. package/src/state/faults.ts +73 -0
  119. package/src/state/format.ts +50 -0
  120. package/src/state/fs.ts +100 -0
  121. package/src/state/items.ts +189 -0
  122. package/src/state/open.ts +80 -0
  123. package/src/state/ops.ts +76 -0
  124. package/src/state/records.ts +35 -0
  125. package/src/state/runs.ts +99 -0
  126. package/src/state/saved.ts +119 -0
  127. package/src/status/file.ts +49 -0
  128. package/src/status/format.ts +132 -0
  129. package/src/status/sections.ts +14 -0
  130. package/src/status/version.ts +2 -0
  131. package/src/time.ts +7 -0
  132. package/src/worker/alignment-report.ts +18 -0
  133. package/src/worker/answers.ts +153 -0
  134. package/src/worker/base-check.ts +46 -0
  135. package/src/worker/checks.ts +26 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +508 -0
  138. package/src/worker/lifecycle.ts +97 -0
  139. package/src/worker/merged.ts +29 -0
  140. package/src/worker/open.ts +100 -0
  141. package/src/worker/prose-run.ts +56 -0
  142. package/src/worker/questions.ts +89 -0
  143. package/src/worker/scheduler.ts +135 -0
  144. package/src/worker/signature.ts +41 -0
  145. package/src/worker/tally.ts +25 -0
  146. package/src/worker/taste.ts +38 -0
  147. package/src/worker/thin-path.ts +886 -0
  148. package/src/worker/worker.ts +728 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,253 @@
1
+ import { GraphqlResponseError } from "@octokit/graphql";
2
+ import pMemoize from "p-memoize";
3
+ import { z } from "zod";
4
+ import type { Json } from "../config/json.ts";
5
+ import { MERGE_METHODS, type MergeMethod } from "../config/schema.ts";
6
+ import {
7
+ type GitHubClient,
8
+ gitHubClient,
9
+ MERGE_METHOD,
10
+ ownerToken,
11
+ raise,
12
+ } from "./github.ts";
13
+
14
+ /** What the target branch's rules ask of a change that lands on it. */
15
+ export type BranchRules = {
16
+ readonly requiresPullRequest: boolean;
17
+ /** The merge methods a pull request may use; undefined when no rule narrows them. */
18
+ readonly mergeMethods: readonly MergeMethod[] | undefined;
19
+ };
20
+
21
+ export type Pull = {
22
+ readonly id: string;
23
+ readonly number: number;
24
+ readonly url: string;
25
+ readonly state: "OPEN" | "MERGED" | "CLOSED";
26
+ readonly autoMerge: boolean;
27
+ /** Its branch is behind the base, which a strict required check makes wait. */
28
+ readonly behind: boolean;
29
+ };
30
+
31
+ /** Pull requests on the repo a run's changes land in. */
32
+ export type PullRequests = {
33
+ /** The rules read once and kept; `fresh` reads them again, as after a push the remote refused. */
34
+ readonly rules: (base: string, fresh?: boolean) => Promise<BranchRules>;
35
+ /** The newest pull request from `head`, in any state. */
36
+ readonly find: (head: string) => Promise<Pull | undefined>;
37
+ readonly open: (change: {
38
+ head: string;
39
+ base: string;
40
+ title: string;
41
+ body: string;
42
+ }) => Promise<Pull>;
43
+ /** Turns auto-merge on or off. A pull request whose checks already passed takes no auto-merge, so it merges now. */
44
+ readonly autoMerge: (
45
+ pull: Pull,
46
+ on: boolean,
47
+ method: MergeMethod,
48
+ ) => Promise<"armed" | "merged" | "off">;
49
+ readonly update: (pull: Pull) => Promise<void>;
50
+ /** One comment on the pull request. */
51
+ readonly comment: (pull: Pull, body: string) => Promise<void>;
52
+ };
53
+
54
+ const Rule = z.looseObject({
55
+ type: z.string(),
56
+ parameters: z
57
+ .looseObject({
58
+ allowed_merge_methods: z.array(z.enum(MERGE_METHODS)).optional(),
59
+ })
60
+ .optional(),
61
+ });
62
+
63
+ const PULL_REQUEST_RULE = "pull_request";
64
+
65
+ const PullNode = z.object({
66
+ id: z.string(),
67
+ number: z.int(),
68
+ url: z.string(),
69
+ state: z.enum(["OPEN", "MERGED", "CLOSED"]),
70
+ mergeStateStatus: z.string(),
71
+ autoMergeRequest: z.object({ enabledAt: z.string().nullable() }).nullable(),
72
+ });
73
+
74
+ const PULL_FIELDS =
75
+ "id number url state mergeStateStatus autoMergeRequest { enabledAt }";
76
+
77
+ const BEHIND = "BEHIND";
78
+
79
+ const PULLS = `query PullsFrom($owner: String!, $name: String!, $head: String!) {
80
+ repository(owner: $owner, name: $name) { id pullRequests(headRefName: $head, first: 1, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_FIELDS} } } }
81
+ }`;
82
+
83
+ const OPEN_PULL = `mutation OpenPull($repository: ID!, $base: String!, $head: String!, $title: String!, $body: String!) {
84
+ createPullRequest(input: { repositoryId: $repository, baseRefName: $base, headRefName: $head, title: $title, body: $body }) { pullRequest { ${PULL_FIELDS} } }
85
+ }`;
86
+
87
+ const ENABLE_AUTO_MERGE = `mutation EnableAutoMerge($pull: ID!, $mergeMethod: PullRequestMergeMethod!) {
88
+ enablePullRequestAutoMerge(input: { pullRequestId: $pull, mergeMethod: $mergeMethod }) { clientMutationId }
89
+ }`;
90
+
91
+ const DISABLE_AUTO_MERGE = `mutation DisableAutoMerge($pull: ID!) {
92
+ disablePullRequestAutoMerge(input: { pullRequestId: $pull }) { clientMutationId }
93
+ }`;
94
+
95
+ const MERGE_NOW = `mutation MergeNow($pull: ID!, $mergeMethod: PullRequestMergeMethod!) {
96
+ mergePullRequest(input: { pullRequestId: $pull, mergeMethod: $mergeMethod }) { clientMutationId }
97
+ }`;
98
+
99
+ const COMMENT = `mutation Comment($pull: ID!, $body: String!) {
100
+ addComment(input: { subjectId: $pull, body: $body }) { clientMutationId }
101
+ }`;
102
+
103
+ const UPDATE_BRANCH = `mutation UpdateBranch($pull: ID!) {
104
+ updatePullRequestBranch(input: { pullRequestId: $pull }) { clientMutationId }
105
+ }`;
106
+
107
+ const PullsReply = z.object({
108
+ repository: z.object({
109
+ id: z.string(),
110
+ pullRequests: z.object({ nodes: z.array(PullNode) }),
111
+ }),
112
+ });
113
+
114
+ const Opened = z.object({
115
+ createPullRequest: z.object({ pullRequest: PullNode }),
116
+ });
117
+
118
+ const Acknowledged = z.looseObject({});
119
+
120
+ /** GitHub refuses auto-merge on a pull request that may merge now. */
121
+ const isMergeableNow = (cause: unknown): boolean =>
122
+ cause instanceof GraphqlResponseError && /clean status/i.test(cause.message);
123
+
124
+ const pullOf = (node: z.infer<typeof PullNode>): Pull => ({
125
+ id: node.id,
126
+ number: node.number,
127
+ url: node.url,
128
+ state: node.state,
129
+ autoMerge: node.autoMergeRequest !== null,
130
+ behind: node.mergeStateStatus === BEHIND,
131
+ });
132
+
133
+ /** The method the owner set when the branch's rules allow it, else the first they allow. */
134
+ export const methodFor = (
135
+ preferred: MergeMethod,
136
+ allowed: readonly MergeMethod[] | undefined,
137
+ ): MergeMethod =>
138
+ allowed === undefined || allowed.includes(preferred)
139
+ ? preferred
140
+ : (allowed[0] ?? preferred);
141
+
142
+ /** Pull requests and branch rules of a GitHub repo, on the owner's own login unless a client is given. `timeoutMs` bounds the `gh auth token` that reads that login. */
143
+ export const gitHubPullRequests = (
144
+ repo: string,
145
+ { timeoutMs, client }: { readonly timeoutMs: number; readonly client?: GitHubClient },
146
+ ): PullRequests => {
147
+ const [owner = "", name = ""] = repo.split("/");
148
+
149
+ const connect = pMemoize(
150
+ async () => client ?? gitHubClient({ token: await ownerToken(timeoutMs) }),
151
+ );
152
+
153
+ const rulesCache = new Map<string, BranchRules>();
154
+
155
+ const graphql = async <T>(
156
+ schema: z.ZodType<T>,
157
+ document: string,
158
+ variables: Readonly<Record<string, Json>>,
159
+ ): Promise<T> =>
160
+ schema.parse(
161
+ await (
162
+ await connect()
163
+ )
164
+ .graphql(document, { owner, name, ...variables })
165
+ .catch(raise),
166
+ );
167
+
168
+ const readRules = pMemoize(
169
+ async (base: string): Promise<BranchRules> => {
170
+ const reply = await (
171
+ await connect()
172
+ )
173
+ .request("GET /repos/{owner}/{repo}/rules/branches/{branch}", {
174
+ owner,
175
+ repo: name,
176
+ branch: base,
177
+ })
178
+ .catch(raise);
179
+
180
+ const rules = z.array(Rule).parse(reply.data);
181
+ const pullRule = rules.find((rule) => rule.type === PULL_REQUEST_RULE);
182
+
183
+ return {
184
+ requiresPullRequest: pullRule !== undefined,
185
+ mergeMethods: pullRule?.parameters?.allowed_merge_methods,
186
+ };
187
+ },
188
+ { cache: rulesCache },
189
+ );
190
+
191
+ const find = async (head: string): Promise<Pull | undefined> => {
192
+ const node = (await graphql(PullsReply, PULLS, { head })).repository
193
+ .pullRequests.nodes[0];
194
+
195
+ return node && pullOf(node);
196
+ };
197
+
198
+ return {
199
+ rules: (base, fresh = false) => {
200
+ if (fresh) rulesCache.delete(base);
201
+
202
+ return readRules(base);
203
+ },
204
+ find,
205
+ open: async ({ head, base, title, body }) => {
206
+ const repository = (await graphql(PullsReply, PULLS, { head })).repository
207
+ .id;
208
+
209
+ return pullOf(
210
+ (
211
+ await graphql(Opened, OPEN_PULL, {
212
+ repository,
213
+ base,
214
+ head,
215
+ title,
216
+ body,
217
+ })
218
+ ).createPullRequest.pullRequest,
219
+ );
220
+ },
221
+ autoMerge: async (pull, on, method) => {
222
+ if (!on) {
223
+ if (pull.autoMerge)
224
+ await graphql(Acknowledged, DISABLE_AUTO_MERGE, { pull: pull.id });
225
+
226
+ return "off";
227
+ }
228
+
229
+ if (pull.autoMerge) return "armed";
230
+
231
+ const mergeMethod = MERGE_METHOD[method];
232
+
233
+ const armed = await (
234
+ await connect()
235
+ )
236
+ .graphql(ENABLE_AUTO_MERGE, { pull: pull.id, mergeMethod })
237
+ .then(
238
+ () => true,
239
+ (cause: unknown) => (isMergeableNow(cause) ? false : raise(cause)),
240
+ );
241
+
242
+ if (armed) return "armed";
243
+
244
+ await graphql(Acknowledged, MERGE_NOW, { pull: pull.id, mergeMethod });
245
+
246
+ return "merged";
247
+ },
248
+ update: async (pull) =>
249
+ void (await graphql(Acknowledged, UPDATE_BRANCH, { pull: pull.id })),
250
+ comment: async (pull, body) =>
251
+ void (await graphql(Acknowledged, COMMENT, { pull: pull.id, body })),
252
+ };
253
+ };
@@ -0,0 +1,156 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { z } from "zod";
5
+ import { ADAPTER_API_VERSION, type Adapter, type AdapterContext, type AdapterFactory, PermanentError } from "../adapter-api.ts";
6
+ import { readSettings } from "../config/settings.ts";
7
+ import { HumConfig } from "../config/schema.ts";
8
+ import { commandTimeoutMs } from "../exec.ts";
9
+ import type { Faults } from "../state/faults.ts";
10
+ import type { Card } from "../status/format.ts";
11
+ import { githubAdapter, repoFromRemote } from "./github.ts";
12
+ import { gitIn, whenGitFailed } from "./git.ts";
13
+ import { type GuardOptions, guardTimings, guarded } from "./guard.ts";
14
+ import { markdownAdapter } from "./markdown.ts";
15
+ import { gitHubPullRequests, type PullRequests } from "./pull-requests.ts";
16
+ import { roundupAdapter } from "./roundup.ts";
17
+
18
+ /** The integration slots `hum.json` `integrations` names, each to an adapter. */
19
+ export const SLOTS = ["work-source", "questions", "answers", "release"] as const;
20
+
21
+ export type Slot = (typeof SLOTS)[number];
22
+
23
+ const MARKDOWN = "markdown";
24
+ const FALLBACK_BASE = "main";
25
+
26
+ /** Slots that use the markdown source when `hum.json` names none; release has no default. */
27
+ const MARKDOWN_SLOTS: readonly Slot[] = ["work-source", "questions", "answers"];
28
+
29
+ /** What the adapters read from `hum.json`; every other key belongs to the worker. */
30
+ const AdapterSettings = z.looseObject({
31
+ integrations: z.partialRecord(z.enum(SLOTS), z.string().min(1)).optional(),
32
+ claimPrefix: HumConfig.shape.claimPrefix,
33
+ itemsDir: HumConfig.shape.itemsDir,
34
+ commitIdentity: HumConfig.shape.commitIdentity,
35
+ readyLabel: HumConfig.shape.readyLabel,
36
+ mergeMethod: HumConfig.shape.mergeMethod,
37
+ ownerBranchPrefix: HumConfig.shape.ownerBranchPrefix,
38
+ writeRaceRetries: HumConfig.shape.writeRaceRetries,
39
+ itemReadsAtOnce: HumConfig.shape.itemReadsAtOnce,
40
+ providerTimeoutSeconds: HumConfig.shape.providerTimeoutSeconds,
41
+ providerBackoff: HumConfig.shape.providerBackoff,
42
+ commandTimeoutSeconds: HumConfig.shape.commandTimeoutSeconds,
43
+ });
44
+
45
+ type AdapterSettings = z.infer<typeof AdapterSettings>;
46
+
47
+ const AdapterModule = z.looseObject({ default: z.custom<AdapterFactory>((value) => value instanceof Function, "must export an adapter factory as its default") });
48
+
49
+ /** The adapter a slot uses: the one `hum.json` names, else the markdown source where that is the default. */
50
+ const adapterNameFor = (slot: Slot, integrations: AdapterSettings["integrations"]): string | undefined =>
51
+ integrations?.[slot] ?? (MARKDOWN_SLOTS.includes(slot) ? MARKDOWN : undefined);
52
+
53
+ type Repo = { readonly path: string; readonly settings: AdapterSettings; readonly context: AdapterContext };
54
+
55
+ const defaultBase = async (repo: string, timeoutMs: number): Promise<string> => {
56
+ const head = await gitIn(repo, { timeoutMs })
57
+ .raw(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
58
+ .catch(whenGitFailed(`origin/${FALLBACK_BASE}`));
59
+
60
+ return head.trim().replace(/^origin\//, "");
61
+ };
62
+
63
+ /** The pull requests of the repo's `origin` when it is on GitHub. */
64
+ const originPulls = async (repo: string, timeoutMs: number): Promise<PullRequests | undefined> => {
65
+ const found = repoFromRemote(await gitIn(repo, { timeoutMs }).raw(["remote", "get-url", "origin"]).catch(whenGitFailed("")));
66
+
67
+ return found === undefined ? undefined : gitHubPullRequests(found, { timeoutMs });
68
+ };
69
+
70
+ const githubRepo = async (repo: string, timeoutMs: number): Promise<string> => {
71
+ const found = repoFromRemote(await gitIn(repo, { timeoutMs }).raw(["remote", "get-url", "origin"]));
72
+
73
+ if (!found) throw new PermanentError("the github adapter needs an `origin` remote on github.com");
74
+
75
+ return found;
76
+ };
77
+
78
+ /** The adapters the engine ships, by the name `hum.json` gives them. */
79
+ const BUILT_IN = {
80
+ [MARKDOWN]: async ({ path, settings, context }) => {
81
+ const timeoutMs = commandTimeoutMs(settings);
82
+
83
+ return markdownAdapter({ repo: path, base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, itemsDir: settings.itemsDir, identity: settings.commitIdentity, writeRaceRetries: settings.writeRaceRetries, itemReadsAtOnce: settings.itemReadsAtOnce, pulls: await originPulls(path, timeoutMs), mergeMethod: settings.mergeMethod, ownerBranchPrefix: settings.ownerBranchPrefix, timeoutMs }, context);
84
+ },
85
+ github: async ({ path, settings, context }) => {
86
+ const timeoutMs = commandTimeoutMs(settings);
87
+
88
+ return githubAdapter({ repo: await githubRepo(path, timeoutMs), base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, readyLabel: settings.readyLabel, mergeMethod: settings.mergeMethod, timeoutMs }, context);
89
+ },
90
+ roundup: async ({ context }) => roundupAdapter({}, context),
91
+ } satisfies Readonly<Record<string, (repo: Repo) => Promise<Adapter>>>;
92
+
93
+ const isBuiltIn = (name: string): name is keyof typeof BUILT_IN => Object.hasOwn(BUILT_IN, name);
94
+
95
+ /** An owner's adapter: the default export of `adapters/<name>.ts` in the repo. */
96
+ const ownerAdapter = async (name: string, { path, context }: Repo): Promise<Adapter> => {
97
+ const file = join(path, "adapters", `${name}.ts`);
98
+
99
+ if (!existsSync(file)) throw new PermanentError(`no adapter "${name}": the engine ships ${Object.keys(BUILT_IN).join(", ")}, and ${file} does not exist`);
100
+
101
+ const loaded = AdapterModule.safeParse(await import(pathToFileURL(file).href));
102
+
103
+ if (!loaded.success) throw new PermanentError(`${file}: ${loaded.error.issues[0]?.message}`);
104
+
105
+ return loaded.data.default(context);
106
+ };
107
+
108
+ /** The card that refuses an adapter written for another API version; undefined for one written for this engine. */
109
+ export const refuseOtherVersion = (name: string, adapter: Adapter, faults: Faults): Card | undefined => {
110
+ if (adapter.apiVersion === ADAPTER_API_VERSION) return undefined;
111
+
112
+ return faults.raise({
113
+ code: "adapter-api-mismatch",
114
+ item: name,
115
+ cause: `Adapter "${name}" implements adapter API ${adapter.apiVersion}; this engine runs ${ADAPTER_API_VERSION}.`,
116
+ fix: `Update ${name} to adapter API ${ADAPTER_API_VERSION}.`,
117
+ });
118
+ };
119
+
120
+ /**
121
+ * The adapter `hum.json` names for each slot, guarded: one the engine ships, else an owner's `adapters/<name>.ts`.
122
+ * A slot with no entry uses the markdown source in `repo`, except release, which has no default. Slots that name
123
+ * the same adapter share one instance.
124
+ */
125
+ export const resolveAdapters = async (
126
+ repo: string,
127
+ { faults, guard, context }: { faults: Faults; guard: Pick<GuardOptions, "lastReady">; context: AdapterContext },
128
+ ): Promise<Partial<Record<Slot, Adapter>>> => {
129
+ const settings = readSettings(repo, AdapterSettings);
130
+
131
+ const slots = SLOTS.flatMap((slot) => {
132
+ const name = adapterNameFor(slot, settings.integrations);
133
+
134
+ return name === undefined ? [] : [[slot, name] as const];
135
+ });
136
+
137
+ const source: Repo = { path: repo, settings, context };
138
+
139
+ const build = async (name: string): Promise<Adapter> => {
140
+ const adapter = await (isBuiltIn(name) ? BUILT_IN[name](source) : ownerAdapter(name, source));
141
+
142
+ if (refuseOtherVersion(name, adapter, faults)) throw new PermanentError(`adapter "${name}" implements another adapter API version`);
143
+
144
+ return guarded(adapter, {
145
+ ...guard,
146
+ provider: name,
147
+ faults,
148
+ ...guardTimings(settings),
149
+ });
150
+ };
151
+
152
+ const names = [...new Set(slots.map(([, name]) => name))];
153
+ const built = new Map(await Promise.all(names.map(async (name) => [name, await build(name)] as const)));
154
+
155
+ return Object.fromEntries(slots.map(([slot, name]) => [slot, built.get(name)]));
156
+ };
@@ -0,0 +1,291 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
3
+ import { z } from "zod";
4
+ import { type Adapter, type AdapterContext, type Answers, type Item, ItemId, PermanentError, type Questions, type Watch, type WorkSource } from "../adapter-api.ts";
5
+ import { hashJson } from "../config/hash.ts";
6
+ import { Json } from "../config/json.ts";
7
+ import { parseArgument } from "./argument.ts";
8
+ import { claimer, isLive } from "./claim.ts";
9
+ import {
10
+ answerMarker,
11
+ commentText,
12
+ filedFollowUp,
13
+ followUpBody,
14
+ followUpNote,
15
+ type Marker,
16
+ cutLine,
17
+ markedLine,
18
+ markerLine,
19
+ parseComment,
20
+ parseLooseJson,
21
+ questionMarker,
22
+ questionText,
23
+ splitMarker,
24
+ } from "./marked.ts";
25
+
26
+ const CLAIM_OPEN = "<!-- hum-claim ";
27
+
28
+ /** An Agent's comment on a Todo is one line of at most this many characters. */
29
+ const COMMENT_LIMIT = 280;
30
+
31
+ /** The digest in a Pad's name, so the same text posts to the same Pad name. */
32
+ const PAD_DIGEST_LENGTH = 8;
33
+
34
+ const TodoId = ItemId.pipe(z.string().regex(/^(0|[1-9]\d*)$/, "a roundup Todo id is a whole number")).transform(Number);
35
+
36
+ const Actor = z.looseObject({ kind: z.string(), id: z.string() });
37
+
38
+ const Todo = z.looseObject({
39
+ id: z.int().nonnegative(),
40
+ title: z.string(),
41
+ body: z.string(),
42
+ done: z.boolean(),
43
+ blocked: z.boolean(),
44
+ updated_at: z.number().optional(),
45
+ owner: Actor.nullable().optional(),
46
+ });
47
+
48
+ type Todo = z.infer<typeof Todo>;
49
+
50
+ const Todos = z.union([z.array(Todo), z.looseObject({ todos: z.array(Todo) }).transform((found) => found.todos)]);
51
+
52
+ const Comment = z.looseObject({ id: z.int().nonnegative(), body: z.string(), created_at: z.number() });
53
+
54
+ type Comment = z.infer<typeof Comment>;
55
+
56
+ const Reply = z.looseObject({
57
+ content: z.array(z.looseObject({ type: z.string(), text: z.string().optional() })).optional(),
58
+ isError: z.boolean().optional(),
59
+ structuredContent: Json.optional(),
60
+ });
61
+
62
+ /** One take or renewal of an item's claim, written as a comment. */
63
+ const ClaimEntry = z.strictObject({ holder: z.string().min(1), at: z.int().nonnegative(), expiresAt: z.int().nonnegative() });
64
+
65
+ type ClaimEntry = z.infer<typeof ClaimEntry>;
66
+
67
+ /** Calls one tool of roundup's MCP server and returns its parsed JSON. A tool that reports an error throws a `PermanentError`. */
68
+ export type ToolCall = (tool: string, args: Record<string, Json>) => Promise<Json>;
69
+
70
+ export type RoundupOptions = {
71
+ /** Replaces the stdio client, for a stub. */
72
+ readonly call?: ToolCall;
73
+ /** The Agent id `rup mcp` acts as. Defaults to `ROUNDUP_AGENT_ID`. */
74
+ readonly agent?: string;
75
+ /** The Project's daemon socket. Defaults to `RUPD_SOCKET`. */
76
+ readonly socket?: string;
77
+ };
78
+
79
+ const environment = (): Record<string, string> => Object.fromEntries(Object.entries(process.env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])));
80
+
81
+ /** A tool's reply: its structured content, else its text as JSON, else the text itself. */
82
+ const replyValue = (tool: string, result: Awaited<ReturnType<Client["callTool"]>>): Json => {
83
+ const reply = Reply.parse(result);
84
+ const text = reply.content?.find((part) => part.type === "text")?.text ?? "";
85
+
86
+ if (reply.isError) throw new PermanentError(`${tool}: ${text.slice(0, 300)}`);
87
+
88
+ if (reply.structuredContent !== undefined) return reply.structuredContent;
89
+
90
+ const json = parseLooseJson(Json, text);
91
+
92
+ return json === undefined ? text : json;
93
+ };
94
+
95
+ /** The stdio client: `rup mcp <agent>` on the Project's socket. Only a run roundup started has both. */
96
+ export const stdioCall = ({ agent, socket }: RoundupOptions) => {
97
+ const who = agent ?? process.env.ROUNDUP_AGENT_ID;
98
+ const path = socket ?? process.env.RUPD_SOCKET;
99
+ let client: Promise<Client> | undefined;
100
+
101
+ if (!who || !path) throw new PermanentError("the roundup adapter runs only in a run roundup started: ROUNDUP_AGENT_ID and RUPD_SOCKET are not both set");
102
+
103
+ const connect = async () => {
104
+ const made = new Client({ name: "hum", version: "0" });
105
+
106
+ await made.connect(new StdioClientTransport({ command: "rup", args: ["mcp", who], env: { ...environment(), RUPD_SOCKET: path } }));
107
+
108
+ return made;
109
+ };
110
+
111
+ const call: ToolCall = async (tool, args) => {
112
+ const result = await (client ??= connect())
113
+ .then((live) => live.callTool({ name: tool, arguments: args }))
114
+ .catch((cause: unknown) => {
115
+ client = undefined;
116
+
117
+ throw cause;
118
+ });
119
+
120
+ return replyValue(tool, result);
121
+ };
122
+
123
+ return {
124
+ call,
125
+ close: async () => {
126
+ const used = client;
127
+
128
+ client = undefined;
129
+ await (await used)?.close();
130
+ },
131
+ };
132
+ };
133
+
134
+ const claimEntryOf = (body: string): ClaimEntry | undefined => {
135
+ const split = splitMarker(body, CLAIM_OPEN);
136
+
137
+ return split && parseLooseJson(ClaimEntry, split.json);
138
+ };
139
+
140
+ /** A later entry takes over when no claim stands, the standing one ended before it was made, or its holder renews. */
141
+ const takesOver = (current: ClaimEntry | undefined, entry: ClaimEntry): boolean => !current || current.expiresAt <= entry.at || current.holder === entry.holder;
142
+
143
+ /** The claim that stands after the comments' order. The daemon orders comments, so every worker folds the same list to the same winner. */
144
+ const standingEntry = (comments: readonly Comment[]): ClaimEntry | undefined =>
145
+ comments.reduce<ClaimEntry | undefined>((current, comment) => {
146
+ const entry = claimEntryOf(comment.body);
147
+
148
+ return entry && takesOver(current, entry) ? entry : current;
149
+ }, undefined);
150
+
151
+ /** Open, unblocked and unassigned: a Todo nobody else has taken. */
152
+ const isOpenToTake = (todo: Todo): boolean => !todo.done && !todo.blocked && !todo.owner;
153
+
154
+ const fitsOneComment = (text: string): boolean => !text.includes("\n") && text.length <= COMMENT_LIMIT;
155
+
156
+ type Whole = Adapter & {
157
+ readonly workSource: WorkSource;
158
+ readonly questions: Questions;
159
+ readonly answers: Answers;
160
+ /** Always 0: roundup's socket is local and has no rate limit. */
161
+ readonly spent: () => number;
162
+ readonly close: () => Promise<void>;
163
+ };
164
+
165
+ /**
166
+ * roundup as a work source, through its MCP server over stdio: Todos are items and their comments are the thread.
167
+ * A Todo is ready while it is open, unblocked, unassigned and holds no live claim. A claim is a comment, so the
168
+ * daemon's comment order picks the winner. roundup has no release step.
169
+ */
170
+ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext): Whole => {
171
+ const client = options.call ? { call: options.call, close: async () => {} } : stdioCall(options);
172
+ const { call } = client;
173
+
174
+ const comments = async (id: string) => Comment.array().parse(await call("todo_comments", { id: parseArgument(TodoId, id) }));
175
+
176
+ const todo = async (id: string) => Todo.parse(await call("todo_get", { id: parseArgument(TodoId, id) }));
177
+
178
+ const todos = async () => Todos.parse(await call("todo_list", {}));
179
+
180
+ const post = async (id: string, text: string): Promise<void> => {
181
+ if (!fitsOneComment(text)) throw new PermanentError(`a roundup comment is one line of at most ${COMMENT_LIMIT} characters`);
182
+
183
+ await call("todo_comment", { id: parseArgument(TodoId, id), body: text });
184
+ };
185
+
186
+ /** A text too long for one comment goes whole into a Pad; the comment holds its first words and the Pad's name. */
187
+ const postInPad = async (id: string, marker: Marker | undefined, text: string): Promise<void> => {
188
+ const name = `hum ${id} ${hashJson(text).slice(0, PAD_DIGEST_LENGTH)}`;
189
+
190
+ await call("pad_create", { name, text });
191
+ await post(id, cutLine(marker, text, ` … full text in Pad "${name}"`, COMMENT_LIMIT));
192
+ };
193
+
194
+ const fitsMarked = (marker: Marker, text: string): boolean => {
195
+ try {
196
+ markedLine(marker, text, COMMENT_LIMIT);
197
+
198
+ return true;
199
+ } catch (cause) {
200
+ if (cause instanceof PermanentError) return false;
201
+
202
+ throw cause;
203
+ }
204
+ };
205
+
206
+ const postMarked = async (id: string, marker: Marker, text: string): Promise<void> =>
207
+ fitsMarked(marker, text) ? post(id, markedLine(marker, text, COMMENT_LIMIT)) : postInPad(id, marker, text);
208
+
209
+ const postPlain = async (id: string, text: string): Promise<void> => (fitsOneComment(text) ? post(id, text) : postInPad(id, undefined, text));
210
+
211
+ const standingClaim = (id: string, list: readonly Comment[]) => {
212
+ const entry = standingEntry(list);
213
+
214
+ return entry && { claim: { item: id, holder: entry.holder, expiresAt: entry.expiresAt } };
215
+ };
216
+
217
+ const isFree = (id: string, list: readonly Comment[]): boolean => !isLive(standingClaim(id, list)?.claim, now());
218
+
219
+ const take = claimer(
220
+ {
221
+ standing: async (id) => standingClaim(id, await comments(id)),
222
+ isReady: async (id) => isOpenToTake(await todo(id)),
223
+ write: async (claim) => {
224
+ const entry: ClaimEntry = { holder: claim.holder, at: now(), expiresAt: claim.expiresAt };
225
+
226
+ await post(claim.item, `${markerLine(ClaimEntry, entry, CLAIM_OPEN)} claimed by ${claim.holder}`);
227
+
228
+ return standingEntry(await comments(claim.item))?.holder === claim.holder;
229
+ },
230
+ },
231
+ now,
232
+ );
233
+
234
+ const threadOf = (list: readonly Comment[]) => list.flatMap((comment) => (claimEntryOf(comment.body) === undefined ? [parseComment(comment.body, comment.created_at)] : []));
235
+
236
+ /** What `watch` hashes for one Todo. Comments are no Todo change, so each open Todo's comment ids count too. */
237
+ const watchedParts = async (found: Todo): Promise<Json> => ({
238
+ id: found.id,
239
+ updatedAt: found.updated_at ?? null,
240
+ done: found.done,
241
+ owner: found.owner?.id ?? null,
242
+ comments: found.done ? [] : (await comments(String(found.id))).map((comment) => comment.id),
243
+ });
244
+
245
+ return {
246
+ apiVersion: 1,
247
+ spent: () => 0,
248
+ close: client.close,
249
+ workSource: {
250
+ listReady: async () => {
251
+ const open = (await todos()).filter(isOpenToTake);
252
+ const free = await Promise.all(open.map(async (found) => isFree(String(found.id), await comments(String(found.id)))));
253
+
254
+ return open.flatMap((found, index) => (free[index] ? [{ id: String(found.id), title: found.title }] : []));
255
+ },
256
+ read: async (id): Promise<Item> => {
257
+ const [found, list] = await Promise.all([todo(id), comments(id)]);
258
+
259
+ return { id, title: found.title, body: found.body, ready: isOpenToTake(found) && isFree(id, list), thread: threadOf(list) };
260
+ },
261
+ claim: (id, holder, ttlMs) => take("claim", parseArgument(ItemId, id), holder, ttlMs),
262
+ renew: (id, holder, ttlMs) => take("renew", parseArgument(ItemId, id), holder, ttlMs),
263
+ comment: (id, text) => postPlain(id, commentText(text)),
264
+ fileFollowUp: async (from, { title, body }) => {
265
+ const filed = filedFollowUp((await comments(from)).map((comment) => comment.body), title);
266
+
267
+ if (filed !== undefined) return { id: filed, title };
268
+
269
+ const made = Todo.parse(await call("todo_create", { title, body: followUpBody(body, `#${from}`) }));
270
+ const note = followUpNote(title, String(made.id));
271
+
272
+ await postMarked(from, note.marker, note.text);
273
+
274
+ return { id: String(made.id), title };
275
+ },
276
+ },
277
+ questions: {
278
+ ask: (id, question) => postMarked(id, questionMarker(question.options), questionText(question)),
279
+ decide: (id, text) => postMarked(id, { kind: "decision" }, text),
280
+ },
281
+ answers: {
282
+ answer: (id, { text, option }) => postMarked(id, answerMarker(option), text),
283
+ /** The socket is local: none of this spends rate limit. */
284
+ watch: async (since?: string): Promise<Watch> => {
285
+ const token = hashJson(await Promise.all((await todos()).map(watchedParts)));
286
+
287
+ return { token, changed: token !== since };
288
+ },
289
+ },
290
+ };
291
+ };