@moo.md/hum 0.1.0 → 0.2.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 (108) hide show
  1. package/package.json +2 -2
  2. package/scripts/eval.ts +88 -50
  3. package/src/adapter-api.ts +46 -14
  4. package/src/adapters/admit.ts +2 -2
  5. package/src/adapters/argument.ts +1 -1
  6. package/src/adapters/claim.ts +18 -15
  7. package/src/adapters/claude-bg.ts +50 -27
  8. package/src/adapters/claude-p.ts +18 -23
  9. package/src/adapters/contract.ts +22 -10
  10. package/src/adapters/each-call.ts +9 -0
  11. package/src/adapters/fake.ts +6 -6
  12. package/src/adapters/git.ts +10 -18
  13. package/src/adapters/github-client.ts +102 -0
  14. package/src/adapters/github.ts +34 -142
  15. package/src/adapters/guard.ts +20 -9
  16. package/src/adapters/history.ts +12 -15
  17. package/src/adapters/item-file.ts +1 -1
  18. package/src/adapters/markdown.ts +49 -42
  19. package/src/adapters/marked.ts +6 -12
  20. package/src/adapters/model-call.ts +4 -4
  21. package/src/adapters/once.ts +5 -5
  22. package/src/adapters/owner-commit.ts +13 -11
  23. package/src/adapters/pull-requests.ts +11 -13
  24. package/src/adapters/registry.ts +7 -7
  25. package/src/adapters/roundup.ts +27 -35
  26. package/src/adapters/serial.ts +4 -5
  27. package/src/adapters/transcript.ts +13 -8
  28. package/src/cli/main.ts +1 -0
  29. package/src/cli/ops.ts +32 -14
  30. package/src/cli/service.ts +14 -8
  31. package/src/cli/setup.ts +8 -3
  32. package/src/cli/shared-watch.ts +3 -3
  33. package/src/config/checks.ts +14 -18
  34. package/src/config/machine.ts +5 -7
  35. package/src/config/refusal.ts +7 -0
  36. package/src/config/schema.ts +7 -7
  37. package/src/config/settings.ts +17 -2
  38. package/src/config/state-map.ts +5 -3
  39. package/src/decide/alignment.ts +4 -4
  40. package/src/decide/answer.ts +24 -22
  41. package/src/decide/kind.ts +1 -6
  42. package/src/decide/labels.ts +9 -9
  43. package/src/decide/merge.ts +6 -7
  44. package/src/decide/prose.ts +4 -4
  45. package/src/decide/question.ts +23 -20
  46. package/src/decide/review.ts +4 -2
  47. package/src/decide/risk.ts +25 -19
  48. package/src/decide/taste.ts +3 -3
  49. package/src/exec.ts +4 -3
  50. package/src/index.ts +14 -13
  51. package/src/loop/check-item.ts +3 -3
  52. package/src/loop/ci.ts +1 -1
  53. package/src/loop/github.ts +2 -2
  54. package/src/loop/groups.ts +13 -6
  55. package/src/loop/memory.ts +40 -28
  56. package/src/loop/notes.ts +5 -5
  57. package/src/loop/pair.ts +1 -1
  58. package/src/loop/pass.ts +18 -12
  59. package/src/loop/proof.ts +9 -7
  60. package/src/loop/prove-item.ts +1 -1
  61. package/src/loop/records.ts +12 -13
  62. package/src/loop/signals.ts +6 -6
  63. package/src/measure/inputs.ts +1 -1
  64. package/src/measure/measure.ts +4 -4
  65. package/src/measure/rate.ts +2 -0
  66. package/src/service/ci-tick.ts +2 -2
  67. package/src/service/supervise.ts +3 -2
  68. package/src/service/token.ts +3 -3
  69. package/src/service/wake.ts +2 -2
  70. package/src/service/workflows.ts +2 -2
  71. package/src/setup/propose.ts +4 -4
  72. package/src/setup/prove.ts +18 -12
  73. package/src/setup/scan.ts +31 -24
  74. package/src/setup/shipped.ts +8 -2
  75. package/src/setup/tables.ts +4 -3
  76. package/src/setup/waits.ts +9 -11
  77. package/src/setup/write.ts +17 -10
  78. package/src/slots/pool.ts +32 -24
  79. package/src/state/events.ts +1 -1
  80. package/src/state/faults.ts +13 -5
  81. package/src/state/format.ts +2 -2
  82. package/src/state/items.ts +9 -10
  83. package/src/state/open.ts +2 -2
  84. package/src/state/ops.ts +16 -10
  85. package/src/state/records.ts +5 -5
  86. package/src/state/runs.ts +33 -26
  87. package/src/state/saved.ts +44 -32
  88. package/src/status/file.ts +20 -1
  89. package/src/status/format.ts +47 -57
  90. package/src/status/sections.ts +2 -2
  91. package/src/worker/alignment-report.ts +4 -5
  92. package/src/worker/answers.ts +26 -24
  93. package/src/worker/base-check.ts +2 -2
  94. package/src/worker/kind.ts +23 -19
  95. package/src/worker/land.ts +114 -126
  96. package/src/worker/merged.ts +9 -7
  97. package/src/worker/open.ts +14 -12
  98. package/src/worker/prose-run.ts +3 -3
  99. package/src/worker/questions.ts +15 -12
  100. package/src/worker/scheduler.ts +4 -4
  101. package/src/worker/signature.ts +3 -3
  102. package/src/worker/tally.ts +0 -2
  103. package/src/worker/taste.ts +6 -15
  104. package/src/worker/thin-path.ts +148 -121
  105. package/src/worker/thread.ts +25 -0
  106. package/src/worker/worker.ts +77 -47
  107. package/surface.json +632 -2197
  108. package/src/slots/scan.ts +0 -26
@@ -1,9 +1,10 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
2
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
3
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";
4
+ import { ADAPTER_API_VERSION, type AdapterContext, type Answers, Holder, type Integrations, type Item, ItemId, PermanentError, type Questions, type Watch, type WorkSource } from "../adapter-api.ts";
5
5
  import { hashJson } from "../config/hash.ts";
6
6
  import { Json } from "../config/json.ts";
7
+ import type { Env } from "../exec.ts";
7
8
  import { parseArgument } from "./argument.ts";
8
9
  import { claimer, isLive } from "./claim.ts";
9
10
  import {
@@ -32,7 +33,7 @@ const COMMENT_LIMIT = 280;
32
33
  /** The digest in a Pad's name, so the same text posts to the same Pad name. */
33
34
  const PAD_DIGEST_LENGTH = 8;
34
35
 
35
- const TodoId = ItemId.pipe(z.string().regex(/^(0|[1-9]\d*)$/, "a roundup Todo id is a whole number")).transform(Number);
36
+ const TodoId = ItemId.refine((id) => /^(0|[1-9]\d*)$/.test(id), "a roundup Todo id is a whole number").transform(Number);
36
37
 
37
38
  const Actor = z.looseObject({ kind: z.string(), id: z.string() });
38
39
 
@@ -61,7 +62,7 @@ const Reply = z.looseObject({
61
62
  });
62
63
 
63
64
  /** One take or renewal of an item's claim, written as a comment. */
64
- const ClaimEntry = z.strictObject({ holder: z.string().min(1), at: z.int().nonnegative(), expiresAt: z.int().nonnegative() });
65
+ const ClaimEntry = z.object({ holder: Holder, at: z.int().nonnegative(), expiresAt: z.int().nonnegative() });
65
66
 
66
67
  type ClaimEntry = z.infer<typeof ClaimEntry>;
67
68
 
@@ -77,7 +78,7 @@ export type RoundupOptions = {
77
78
  readonly socket?: string;
78
79
  };
79
80
 
80
- const environment = (): Record<string, string> => Object.fromEntries(Object.entries(process.env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])));
81
+ const defined = (env: Env): Record<string, string> => Object.fromEntries(Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])));
81
82
 
82
83
  /** A tool's reply: its structured content, else its text as JSON, else the text itself. */
83
84
  const replyValue = (tool: string, result: Awaited<ReturnType<Client["callTool"]>>): Json => {
@@ -94,9 +95,9 @@ const replyValue = (tool: string, result: Awaited<ReturnType<Client["callTool"]>
94
95
  };
95
96
 
96
97
  /** The stdio client: `rup mcp <agent>` on the Project's socket. Only a run roundup started has both. */
97
- export const stdioCall = ({ agent, socket }: RoundupOptions) => {
98
- const who = agent ?? process.env.ROUNDUP_AGENT_ID;
99
- const path = socket ?? process.env.RUPD_SOCKET;
98
+ export const stdioCall = ({ agent, socket }: RoundupOptions, env: Env) => {
99
+ const who = agent ?? env.ROUNDUP_AGENT_ID;
100
+ const path = socket ?? env.RUPD_SOCKET;
100
101
  let client: Promise<Client> | undefined;
101
102
 
102
103
  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");
@@ -104,7 +105,7 @@ export const stdioCall = ({ agent, socket }: RoundupOptions) => {
104
105
  const connect = async () => {
105
106
  const made = new Client({ name: "hum", version: "0" });
106
107
 
107
- await made.connect(new StdioClientTransport({ command: "rup", args: ["mcp", who], env: { ...environment(), RUPD_SOCKET: path } }));
108
+ await made.connect(new StdioClientTransport({ command: "rup", args: ["mcp", who], env: { ...defined(env), RUPD_SOCKET: path } }));
108
109
 
109
110
  return made;
110
111
  };
@@ -139,22 +140,22 @@ const claimEntryOf = (body: string): ClaimEntry | undefined => {
139
140
  };
140
141
 
141
142
  /** A later entry takes over when no claim stands, the standing one ended before it was made, or its holder renews. */
142
- const takesOver = (current: ClaimEntry | undefined, entry: ClaimEntry): boolean => !current || current.expiresAt <= entry.at || current.holder === entry.holder;
143
+ const doesTakeOver = (current: ClaimEntry | undefined, entry: ClaimEntry): boolean => !current || current.expiresAt <= entry.at || current.holder === entry.holder;
143
144
 
144
145
  /** The claim that stands after the comments' order. The daemon orders comments, so every worker folds the same list to the same winner. */
145
146
  const standingEntry = (comments: readonly Comment[]): ClaimEntry | undefined =>
146
147
  comments.reduce<ClaimEntry | undefined>((current, comment) => {
147
148
  const entry = claimEntryOf(comment.body);
148
149
 
149
- return entry && takesOver(current, entry) ? entry : current;
150
+ return entry && doesTakeOver(current, entry) ? entry : current;
150
151
  }, undefined);
151
152
 
152
153
  /** Open, unblocked and unassigned: a Todo nobody else has taken. */
153
154
  const isOpenToTake = (todo: Todo): boolean => !todo.done && !todo.blocked && !todo.owner;
154
155
 
155
- const fitsOneComment = (text: string): boolean => !text.includes("\n") && text.length <= COMMENT_LIMIT;
156
+ const doesFitOneComment = (text: string): boolean => !text.includes("\n") && text.length <= COMMENT_LIMIT;
156
157
 
157
- type Whole = Adapter & {
158
+ type Whole = Integrations & {
158
159
  readonly workSource: WorkSource;
159
160
  readonly questions: Questions;
160
161
  readonly answers: Answers;
@@ -168,8 +169,8 @@ type Whole = Adapter & {
168
169
  * A Todo is ready while it is open, unblocked, unassigned and holds no live claim. A claim is a comment, so the
169
170
  * daemon's comment order picks the winner. roundup has no release step.
170
171
  */
171
- export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext): Whole => {
172
- const client = options.call ? { call: options.call, close: async () => {} } : stdioCall(options);
172
+ export const roundupAdapter = (options: RoundupOptions, { now, env }: AdapterContext): Whole => {
173
+ const client = options.call ? { call: options.call, close: async () => {} } : stdioCall(options, env);
173
174
  const { call } = client;
174
175
 
175
176
  const comments = async (id: string) => Comment.array().parse(await call("todo_comments", { id: parseArgument(TodoId, id) }));
@@ -179,7 +180,7 @@ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext)
179
180
  const todos = async () => Todos.parse(await call("todo_list", {}));
180
181
 
181
182
  const post = async (id: string, text: string): Promise<void> => {
182
- if (!fitsOneComment(text)) throw new PermanentError(`a roundup comment is one line of at most ${COMMENT_LIMIT} characters`);
183
+ if (!doesFitOneComment(text)) throw new PermanentError(`a roundup comment is one line of at most ${COMMENT_LIMIT} characters`);
183
184
 
184
185
  await call("todo_comment", { id: parseArgument(TodoId, id), body: text });
185
186
  };
@@ -192,30 +193,21 @@ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext)
192
193
  await post(id, cutLine(marker, text, ` … full text in Pad "${name}"`, COMMENT_LIMIT));
193
194
  };
194
195
 
195
- const fitsMarked = (marker: Marker, text: string): boolean => {
196
- try {
197
- markedLine(marker, text, COMMENT_LIMIT);
196
+ const postMarked = async (id: string, marker: Marker, text: string): Promise<void> => {
197
+ const line = markedLine(marker, text);
198
198
 
199
- return true;
200
- } catch (cause) {
201
- if (cause instanceof PermanentError) return false;
202
-
203
- throw cause;
204
- }
199
+ return line.length <= COMMENT_LIMIT ? post(id, line) : postInPad(id, marker, text);
205
200
  };
206
201
 
207
- const postMarked = async (id: string, marker: Marker, text: string): Promise<void> =>
208
- fitsMarked(marker, text) ? post(id, markedLine(marker, text, COMMENT_LIMIT)) : postInPad(id, marker, text);
209
-
210
- const postPlain = async (id: string, text: string): Promise<void> => (fitsOneComment(text) ? post(id, text) : postInPad(id, undefined, text));
202
+ const postPlain = async (id: string, text: string): Promise<void> => (doesFitOneComment(text) ? post(id, text) : postInPad(id, undefined, text));
211
203
 
212
- const standingClaim = (id: string, list: readonly Comment[]) => {
204
+ const standingClaim = (id: ItemId, list: readonly Comment[]) => {
213
205
  const entry = standingEntry(list);
214
206
 
215
207
  return entry && { claim: { item: id, holder: entry.holder, expiresAt: entry.expiresAt } };
216
208
  };
217
209
 
218
- const isFree = (id: string, list: readonly Comment[]): boolean => !isLive(standingClaim(id, list)?.claim, now());
210
+ const isFree = (id: ItemId, list: readonly Comment[]): boolean => !isLive(standingClaim(id, list)?.claim, now());
219
211
 
220
212
  const take = claimer(
221
213
  {
@@ -244,15 +236,15 @@ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext)
244
236
  });
245
237
 
246
238
  return {
247
- apiVersion: 1,
239
+ apiVersion: ADAPTER_API_VERSION,
248
240
  spent: () => 0,
249
241
  close: client.close,
250
242
  workSource: {
251
243
  listReady: async () => {
252
- const open = (await todos()).filter(isOpenToTake);
253
- const free = await Promise.all(open.map(async (found) => isFree(String(found.id), await comments(String(found.id)))));
244
+ const open = (await todos()).filter(isOpenToTake).map((found) => ({ id: ItemId.parse(String(found.id)), title: found.title }));
245
+ const free = await Promise.all(open.map(async ({ id }) => isFree(id, await comments(id))));
254
246
 
255
- return open.flatMap((found, index) => (free[index] ? [{ id: String(found.id), title: found.title }] : []));
247
+ return open.filter((_, index) => free[index]);
256
248
  },
257
249
  read: async (id): Promise<Item> => {
258
250
  const [found, list] = await Promise.all([todo(id), comments(id)]);
@@ -268,7 +260,7 @@ export const roundupAdapter = (options: RoundupOptions, { now }: AdapterContext)
268
260
  if (filed !== undefined) return { id: filed, title };
269
261
 
270
262
  const created = async () => Todo.parse(await call("todo_create", { title, body: followUpBody(body, `#${from}`) })).id;
271
- const id = String((await todos()).find(isFollowUpOf(`#${from}`, title))?.id ?? (await created()));
263
+ const id = ItemId.parse(String((await todos()).find(isFollowUpOf(`#${from}`, title))?.id ?? (await created())));
272
264
  const note = followUpNote(title, id);
273
265
 
274
266
  await postMarked(from, note.marker, note.text);
@@ -1,15 +1,14 @@
1
1
  import PQueue from "p-queue";
2
- import type { Adapter } from "../adapter-api.ts";
2
+ import type { Integrations } from "../adapter-api.ts";
3
+ import { eachCall } from "./each-call.ts";
3
4
 
4
- // SAFETY: every member of an integration role is an async method; each is replaced by one with the same signature.
5
- const inOrder = <R extends object>(role: R | undefined, queue: PQueue): R | undefined =>
6
- role && (Object.fromEntries(Object.entries(role).map(([name, member]) => [name, member instanceof Function ? (...args: unknown[]) => queue.add(async () => member.apply(role, args)) : member])) as R);
5
+ const inOrder = <R extends object>(role: R | undefined, queue: PQueue): R | undefined => role && eachCall<R, R>(role, (call) => async (...args) => queue.add(async () => call(...args)));
7
6
 
8
7
  /**
9
8
  * Runs an adapter's calls one at a time. Runs that go side by side share one adapter, and an adapter
10
9
  * that keeps a clone, as the markdown source does, must not take two writes into it at once.
11
10
  */
12
- export const serialized = (adapter: Adapter): Adapter => {
11
+ export const serialized = (adapter: Integrations): Integrations => {
13
12
  const queue = new PQueue({ concurrency: 1 });
14
13
 
15
14
  return {
@@ -4,7 +4,7 @@ import { epochMs } from "./limit.ts";
4
4
  /** Tokens a run adds to the item's bill: input, output and cache writes. Cache reads are not counted. */
5
5
  export const billed = (input: number, output: number, cacheWrite: number): number => input + output + cacheWrite;
6
6
 
7
- const Counts = {
7
+ export const Counts = {
8
8
  input_tokens: z.number().default(0),
9
9
  output_tokens: z.number().default(0),
10
10
  cache_creation_input_tokens: z.number().default(0),
@@ -72,13 +72,18 @@ const parseRow = (line: string): Row | undefined => {
72
72
  };
73
73
 
74
74
  const readRow = (t: RunTranscript, row: Row | undefined): RunTranscript => {
75
- if (row?.kind === "limit") return { ...t, limit: { resetsAt: row.resetsAt, text: row.text } };
76
-
77
- if (row?.kind === "api-error") return { ...t, apiError: row.error };
78
-
79
- if (row?.kind === "message") return { ...t, messages: { ...t.messages, [row.id]: row.spent } };
80
-
81
- return row?.kind === "structured" ? { ...t, structured: { data: row.data, at: row.at } } : t;
75
+ switch (row?.kind) {
76
+ case undefined:
77
+ return t;
78
+ case "limit":
79
+ return { ...t, limit: { resetsAt: row.resetsAt, text: row.text } };
80
+ case "api-error":
81
+ return { ...t, apiError: row.error };
82
+ case "message":
83
+ return { ...t, messages: { ...t.messages, [row.id]: row.spent } };
84
+ case "structured":
85
+ return { ...t, structured: { data: row.data, at: row.at } };
86
+ }
82
87
  };
83
88
 
84
89
  const EMPTY: RunTranscript = { messages: {}, structured: undefined, apiError: undefined, limit: undefined };
package/src/cli/main.ts CHANGED
@@ -3,6 +3,7 @@ import { runCli } from "./ops.ts";
3
3
 
4
4
  process.exitCode = await runCli(process.argv.slice(2), {
5
5
  cwd: process.cwd(),
6
+ env: process.env,
6
7
  stdout: (text) => void process.stdout.write(text),
7
8
  stderr: (text) => void process.stderr.write(text),
8
9
  });
package/src/cli/ops.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { Command, CommanderError, Option } from "commander";
2
- import { x } from "tinyexec";
3
2
  import { z } from "zod";
4
- import { type ClaimResult, type Item, type ItemRef, PermanentError, Watch } from "../adapter-api.ts";
3
+ import { type ClaimResult, Holder, type Item, ItemId, type ItemRef, PermanentError, Watch } from "../adapter-api.ts";
4
+ import { parseArgument } from "../adapters/argument.ts";
5
5
  import { pushArgs } from "../adapters/git.ts";
6
6
  import { resolveAdapters, type Slot } from "../adapters/registry.ts";
7
7
  import { readSettings } from "../config/settings.ts";
8
+ import { CommandTimedOut, commandTimeoutMs, type Env, exec } from "../exec.ts";
8
9
  import { HumConfig } from "../config/schema.ts";
9
10
  import { dropInto } from "../state/fs.ts";
10
11
  import { defaultStateDir, openState } from "../state/open.ts";
@@ -19,6 +20,7 @@ type Printable = ItemRef[] | ItemRef | Item | ClaimResult | Watch | { readonly o
19
20
 
20
21
  export type Io = {
21
22
  readonly cwd: string;
23
+ readonly env: Env;
22
24
  readonly stdout: (text: string) => void;
23
25
  readonly stderr: (text: string) => void;
24
26
  };
@@ -29,6 +31,7 @@ const EXIT_MISUSED = 2;
29
31
  const OK = { ok: true } as const;
30
32
 
31
33
  const CliSettings = z.looseObject({
34
+ commandTimeoutSeconds: HumConfig.shape.commandTimeoutSeconds,
32
35
  claimExpirySeconds: HumConfig.shape.claimExpirySeconds,
33
36
  watchCacheSeconds: HumConfig.shape.watchCacheSeconds,
34
37
  watchLockSeconds: HumConfig.shape.watchLockSeconds,
@@ -72,19 +75,21 @@ const performed = async (action: Promise<void>): Promise<Printable> => {
72
75
 
73
76
  type Handler = (call: Call) => Promise<Printable>;
74
77
 
78
+ const idOf = (item: string): ItemId => parseArgument(ItemId, item);
79
+
75
80
  const handlers = {
76
81
  "list-ready": ({ slot }) => slot("work-source", (a) => a.workSource).listReady(),
77
82
  claim: ({ slot, item, second: holder, flags, settings }) => {
78
83
  const source = slot("work-source", (a) => a.workSource);
79
84
  const ttlMs = (flags.ttl ?? settings.claimExpirySeconds) * SECOND_MS;
80
85
 
81
- return (flags.renew ? source.renew : source.claim)(item, holder, ttlMs);
86
+ return (flags.renew ? source.renew : source.claim)(idOf(item), parseArgument(Holder, holder), ttlMs);
82
87
  },
83
- read: ({ slot, item }) => slot("work-source", (a) => a.workSource).read(item),
84
- comment: ({ slot, item, text }) => performed(slot("work-source", (a) => a.workSource).comment(item, text)),
85
- ask: ({ slot, item, text, options }) => performed(slot("questions", (a) => a.questions).ask(item, { text: text, options: options.length > 0 ? options : undefined })),
88
+ read: ({ slot, item }) => slot("work-source", (a) => a.workSource).read(idOf(item)),
89
+ comment: ({ slot, item, text }) => performed(slot("work-source", (a) => a.workSource).comment(idOf(item), text)),
90
+ ask: ({ slot, item, text, options }) => performed(slot("questions", (a) => a.questions).ask(idOf(item), { text: text, options: options.length > 0 ? options : undefined })),
86
91
  answer: async ({ slot, item, text, options, inbox, settings }) => {
87
- await slot("answers", (a) => a.answers).answer(item, { text, option: options[0] });
92
+ await slot("answers", (a) => a.answers).answer(idOf(item), { text, option: options[0] });
88
93
  wakeWorker({ inbox, settings }, item);
89
94
 
90
95
  return OK;
@@ -103,21 +108,21 @@ const handlers = {
103
108
  changed: () => wakeWorker({ inbox, settings }, ""),
104
109
  });
105
110
  },
106
- "file-follow-up": ({ slot, item, second, flags }) => slot("work-source", (a) => a.workSource).fileFollowUp(item, { title: second, body: flags.body ?? "" }),
107
- decide: ({ slot, item, text }) => performed(slot("questions", (a) => a.questions).decide(item, text)),
108
- publish: ({ slot, item, second }) => performed(slot("release", (a) => a.release).publish(item, second)),
109
- release: ({ slot, item, second }) => performed(slot("release", (a) => a.release).release(item, second)),
111
+ "file-follow-up": ({ slot, item, second, flags }) => slot("work-source", (a) => a.workSource).fileFollowUp(idOf(item), { title: second, body: flags.body ?? "" }),
112
+ decide: ({ slot, item, text }) => performed(slot("questions", (a) => a.questions).decide(idOf(item), text)),
113
+ publish: ({ slot, item, second }) => performed(slot("release", (a) => a.release).publish(idOf(item), second)),
114
+ release: ({ slot, item, second }) => performed(slot("release", (a) => a.release).release(idOf(item), second)),
110
115
  } as const satisfies Record<Exclude<OpName, "push">, Handler>;
111
116
 
112
117
  const callOf = async (positionals: readonly string[], flags: Flags, io: Io): Promise<Call> => {
113
118
  const stateDir = await defaultStateDir(io.cwd);
114
- const state = openState(stateDir);
119
+ const state = openState(stateDir, { now: Date.now });
115
120
  const settings = readSettings(io.cwd, CliSettings);
116
121
 
117
122
  const adapters = await resolveAdapters(io.cwd, {
118
123
  faults: state.faults,
119
124
  guard: {},
120
- context: { report: (fault) => void state.faults.raise(fault), now: Date.now },
125
+ context: { report: (fault) => void state.faults.raise(fault), now: Date.now, env: io.env },
121
126
  });
122
127
 
123
128
  const [item = "", ...rest] = positionals;
@@ -142,9 +147,22 @@ const callOf = async (positionals: readonly string[], flags: Flags, io: Io): Pro
142
147
  };
143
148
  };
144
149
 
150
+ /** `git push` with the arguments given, under the repo's command time limit; a push past it is stopped and fails. */
151
+ const push = async (positionals: readonly string[], io: Io): Promise<number> => {
152
+ try {
153
+ return (await exec("git", pushArgs(positionals), { timeoutMs: commandTimeoutMs(readSettings(io.cwd, CliSettings)), nodeOptions: { cwd: io.cwd, stdio: "inherit" } })).exitCode ?? EXIT_FAILED;
154
+ } catch (error) {
155
+ if (!(error instanceof CommandTimedOut)) throw error;
156
+
157
+ io.stderr(`hum push: ${error.message}\n`);
158
+
159
+ return EXIT_FAILED;
160
+ }
161
+ };
162
+
145
163
  /** Runs one parsed `hum <op>` and returns its exit code: 0 done, 1 failed, 2 misused. */
146
164
  const perform = async (op: OpName, positionals: readonly string[], flags: Flags, io: Io): Promise<number> => {
147
- if (op === "push") return (await x("git", pushArgs(positionals), { nodeOptions: { cwd: io.cwd, stdio: "inherit" } })).exitCode ?? EXIT_FAILED;
165
+ if (op === "push") return push(positionals, io);
148
166
 
149
167
  try {
150
168
  const printed = await handlers[op](await callOf(positionals, flags, io));
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { hostname } from "node:os";
2
3
  import { join } from "node:path";
3
4
  import type { Command } from "commander";
@@ -15,6 +16,8 @@ import { SECOND_MS } from "../time.ts";
15
16
  import { readStatus } from "../status/file.ts";
16
17
  import { npmLatest, openWorker } from "../worker/open.ts";
17
18
  import type { Io } from "./ops.ts";
19
+ import { Holder } from "../adapter-api.ts";
20
+ import { parseArgument } from "../adapters/argument.ts";
18
21
 
19
22
  const EXIT_OK = 0;
20
23
 
@@ -69,16 +72,19 @@ const serviceSettings = (repo: string): z.infer<typeof ServiceSettings> => {
69
72
  };
70
73
 
71
74
  /** The Mac reads the npm version and when the scheduled workflow last ran; a CI job is that workflow. */
72
- const openFor = async (repo: string, flags: WorkFlags, where: "mac" | "ci") => {
75
+ const openFor = async ({ cwd: repo, env }: Io, flags: WorkFlags, where: "mac" | "ci") => {
73
76
  const timeoutMs = commandTimeoutMs(serviceSettings(repo));
74
77
 
75
78
  return openWorker(repo, {
79
+ now: Date.now,
80
+ env,
81
+ newSessionId: randomUUID,
76
82
  hopeSkills: listHopeSkills(await hopeRoot()),
77
- holder: flags.holder ?? `${where}@${hostname()}`,
83
+ holder: parseArgument(Holder, flags.holder ?? `${where}@${hostname()}`),
78
84
  base: flags.base,
79
85
  where,
80
86
  latestVersion: where === "mac" ? npmLatest : undefined,
81
- ciTick: where === "mac" ? () => readCiTick(repo, "origin", timeoutMs) : undefined,
87
+ ciTick: where === "mac" ? () => readCiTick({ repo, remote: "origin", timeoutMs }) : undefined,
82
88
  });
83
89
  };
84
90
 
@@ -104,7 +110,7 @@ export const addServiceCommands = (root: Command, io: Io, done: (code: number) =
104
110
 
105
111
  onStop(() => abort.abort());
106
112
 
107
- const worker = await openFor(io.cwd, flags, "mac");
113
+ const worker = await openFor(io, flags, "mac");
108
114
  const ended = await worker.serve(abort.signal);
109
115
 
110
116
  io.stderr(`hum work: stopped, ${ended.reason}\n`);
@@ -122,7 +128,7 @@ export const addServiceCommands = (root: Command, io: Io, done: (code: number) =
122
128
  onStop(() => abort.abort());
123
129
 
124
130
  const ended = await supervise({
125
- state: openState(await defaultStateDir(io.cwd)),
131
+ state: openState(await defaultStateDir(io.cwd), { now: Date.now }),
126
132
  spawn: () => spawnWorker(io.cwd, workArgs),
127
133
  now: Date.now,
128
134
  intervalMs: settings.tickIntervalSeconds * SECOND_MS,
@@ -141,16 +147,16 @@ export const addServiceCommands = (root: Command, io: Io, done: (code: number) =
141
147
  withWorkOptions(root.command("wake").description("One CI wake: tick until nothing more starts, record the tick when --event is schedule, and show the cards."))
142
148
  .option("--event <name>", "the GitHub event that started this job")
143
149
  .action(async (flags: WorkFlags & { event?: string }) => {
144
- const worker = await openFor(io.cwd, flags, "ci");
150
+ const worker = await openFor(io, flags, "ci");
145
151
 
146
152
  await wakeUntilQuiet(worker);
147
153
 
148
- if (flags.event === SCHEDULE_EVENT) await recordCiTick(io.cwd, "origin", Date.now(), worker.config.hum.commitIdentity, commandTimeoutMs(worker.config.hum));
154
+ if (flags.event === SCHEDULE_EVENT) await recordCiTick({ repo: io.cwd, remote: "origin", at: Date.now(), identity: worker.config.hum.commitIdentity, timeoutMs: commandTimeoutMs(worker.config.hum) });
149
155
 
150
156
  const status = readStatus(join(await defaultStateDir(io.cwd), "status.json"));
151
157
  const cards = status.ok ? status.status.cards : [];
152
158
 
153
- await reportCards(cards);
159
+ await reportCards(cards, { hasStepSummary: Boolean(process.env.GITHUB_STEP_SUMMARY) });
154
160
  done(cards.length > 0 ? EXIT_CARDS_SHOWN : EXIT_OK);
155
161
  });
156
162
  };
package/src/cli/setup.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { join } from "node:path";
2
3
  import type { Command } from "commander";
3
4
  import { x } from "tinyexec";
@@ -53,6 +54,10 @@ const gh = async (repo: string, args: readonly string[]) => {
53
54
  }
54
55
  };
55
56
 
57
+ type GhOutput = Awaited<ReturnType<typeof gh>>;
58
+
59
+ const isRead = (output: GhOutput): output is NonNullable<GhOutput> => output?.exitCode === 0;
60
+
56
61
  /** The repo's open issues and its label names, from `gh`. Without `gh` or a GitHub remote there are none, and the scan prints no coverage. */
57
62
  const githubFacts = async (repo: string): Promise<GithubFacts | undefined> => {
58
63
  const issues = await gh(repo, ["issue", "list", "--state", "open", "--limit", GH_LIST_LIMIT, "--json", "body,labels"]);
@@ -60,7 +65,7 @@ const githubFacts = async (repo: string): Promise<GithubFacts | undefined> => {
60
65
 
61
66
  const permissions = await gh(repo, ["api", "repos/{owner}/{repo}/actions/permissions/workflow"]);
62
67
 
63
- if (issues?.exitCode !== 0 || labels?.exitCode !== 0 || permissions?.exitCode !== 0) return undefined;
68
+ if (!isRead(issues) || !isRead(labels) || !isRead(permissions)) return undefined;
64
69
 
65
70
  return {
66
71
  items: GhIssues.parse(JSON.parse(issues.stdout)).map(({ body, labels: on }) => ({ body, labels: on.map(({ name }) => name) })),
@@ -118,7 +123,7 @@ export const addSetupCommands = (root: Command, io: Io, done: (code: number) =>
118
123
  .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
119
124
  .option("--item", "run one item through the real claude on a scratch copy; spends live calls")
120
125
  .action(async ({ base, item }: { base: string; item?: true }) => {
121
- const steps = await proveSetup(io.cwd, { hopeSkills: listHopeSkills(await hopeRoot()), base, item: item === true });
126
+ const steps = await proveSetup(io.cwd, { now: Date.now, processEnv: io.env, newSessionId: randomUUID, hopeSkills: listHopeSkills(await hopeRoot()), base, item: item === true });
122
127
 
123
128
  io.stdout(`${steps.map(printStep).join("\n")}\n`);
124
129
  done(steps.some(({ status }) => status === "failed") ? EXIT_FAILED : EXIT_OK);
@@ -131,7 +136,7 @@ export const addSetupCommands = (root: Command, io: Io, done: (code: number) =>
131
136
  .option("--model <id...>", "model ids to measure; default every model the tiers and the cheap call use")
132
137
  .action(async ({ runs, model }: { runs: string; model?: string[] }) => {
133
138
  for (const id of model ?? modelsOf(io.cwd)) {
134
- const ran = await x(process.execPath, [EVAL_SCRIPT, "--model", id, "--runs", runs, "--write", join(io.cwd, ".hum")], { throwOnError: false, nodeOptions: { stdio: "inherit" } });
139
+ const ran = await x(process.execPath, [EVAL_SCRIPT, "--model", id, "--runs", runs, "--write", join(io.cwd, ".hum")], { throwOnError: false, nodeOptions: { cwd: io.cwd, stdio: "inherit" } });
135
140
 
136
141
  if (ran.exitCode !== 0) return done(EXIT_FAILED);
137
142
  }
@@ -11,13 +11,13 @@ const Outcome = z.discriminatedUnion("kind", [
11
11
  ]);
12
12
 
13
13
  /** The last read of what changed, kept for every `hum watch` in the repo. The token is the last one a read returned. */
14
- export const SavedWatch = z.strictObject({
14
+ const SavedWatch = z.strictObject({
15
15
  token: z.string().optional(),
16
16
  checkedAt: z.number().int().nonnegative(),
17
17
  outcome: Outcome,
18
18
  });
19
19
 
20
- export type SavedWatch = z.infer<typeof SavedWatch>;
20
+ type SavedWatch = z.infer<typeof SavedWatch>;
21
21
 
22
22
  export type SharedWatchOptions = {
23
23
  readonly stateDir: string;
@@ -36,7 +36,7 @@ const cachePath = (stateDir: string): string => join(stateDir, "watch.json");
36
36
 
37
37
  const lockPath = (stateDir: string): string => join(stateDir, "watch.lock");
38
38
 
39
- export const loadSavedWatch = (stateDir: string): SavedWatch | undefined =>
39
+ const loadSavedWatch = (stateDir: string): SavedWatch | undefined =>
40
40
  orMissing(() => SavedWatch.parse(readJson(cachePath(stateDir))), undefined);
41
41
 
42
42
  const save = (stateDir: string, saved: SavedWatch): void =>
@@ -24,9 +24,15 @@ const FIXED = new Set<string>(FIXED_PARTS);
24
24
  const isWait = (node: StateNodeJSON) => node.tags?.includes(WAIT_TAG) || node.tags?.includes(OWNER_WAIT_TAG);
25
25
  const isTerminal = (node: StateNodeJSON) => node.type === "final" || node.tags?.includes(STUCK_TAG);
26
26
 
27
- const settles = (value: Transitions) =>
27
+ const doesSettle = (value: Transitions) =>
28
28
  (value ?? []).some((t) => t.target !== undefined || (t.actions?.length ?? 0) > 0);
29
29
 
30
+ /** Whether a wait ends on its own: a timeout with an action that settles it, or a delay that does. */
31
+ const hasTimeoutAction = (node: StateNodeJSON): boolean => (doesSettle(node.onTimeout) && node.timeout !== undefined) || Object.values(node.after ?? {}).some(doesSettle);
32
+
33
+ /** Events xstate sends itself, which no config declares. */
34
+ const isXstateEvent = (event: string): boolean => event.startsWith("xstate.") || event.startsWith("@xstate.");
35
+
30
36
  /** Every state is reachable and reaches done or stuck; every wait has a timeout and an action. */
31
37
  const graphProblems = (kind: string, config: Kind): Problem[] => {
32
38
  const { states, initial } = config.machine;
@@ -67,9 +73,7 @@ const graphProblems = (kind: string, config: Kind): Problem[] => {
67
73
  return Object.entries(states).flatMap(([state, node]): Problem[] => [
68
74
  ...(reachable.has(state) ? [] : [{ problem: "unreachable-state", kind, state } as const]),
69
75
  ...(finishing.has(state) ? [] : [{ problem: "dead-end-state", kind, state } as const]),
70
- ...(isWait(node) && !(settles(node.onTimeout) && node.timeout !== undefined) && !Object.values(node.after ?? {}).some(settles)
71
- ? [{ problem: "wait-without-timeout", kind, state } as const]
72
- : []),
76
+ ...(isWait(node) && !hasTimeoutAction(node) ? [{ problem: "wait-without-timeout", kind, state } as const] : []),
73
77
  ]);
74
78
  };
75
79
 
@@ -139,13 +143,7 @@ export const pickTier = (kind: Pick<Kind, "tiers">, key: { purpose: string; leve
139
143
  /** Every event has a source and a handler, and every event a machine waits on has a source. */
140
144
  const eventProblems = (hum: HumConfig, kinds: Readonly<Record<string, Kind>>): Problem[] => {
141
145
  const parts = new Set<string>([...FIXED_PARTS, ...Object.keys(hum.roles)]);
142
- const handled = new Set<string>();
143
-
144
- for (const kind of Object.values(kinds)) {
145
- for (const node of Object.values(kind.machine.states)) {
146
- for (const event of Object.keys(node.on ?? {})) handled.add(event);
147
- }
148
- }
146
+ const handled = new Set(Object.values(kinds).flatMap((kind) => Object.values(kind.machine.states).flatMap((node) => Object.keys(node.on ?? {}))));
149
147
 
150
148
  return [
151
149
  ...Object.entries(hum.events).flatMap(([event, { source }]): Problem[] => [
@@ -153,9 +151,7 @@ const eventProblems = (hum: HumConfig, kinds: Readonly<Record<string, Kind>>): P
153
151
  ...(handled.has(event) ? [] : [{ problem: "event-without-handler", event } as const]),
154
152
  ]),
155
153
  ...[...handled].flatMap((event): Problem[] =>
156
- event in hum.events || event.startsWith("xstate.") || event.startsWith("@xstate.")
157
- ? []
158
- : [{ problem: "event-without-source", event, source: undefined }],
154
+ event in hum.events || isXstateEvent(event) ? [] : [{ problem: "event-without-source", event, source: undefined }],
159
155
  ),
160
156
  ];
161
157
  };
@@ -171,18 +167,18 @@ const skillProblems = (hum: HumConfig, env: CheckEnv): Problem[] =>
171
167
  );
172
168
 
173
169
  /** A run branch could then share a name, or a folder, with a claim branch. */
174
- const prefixesOverlap = ({ runBranchPrefix, claimPrefix }: Naming): boolean =>
170
+ const doPrefixesOverlap = ({ runBranchPrefix, claimPrefix }: Naming): boolean =>
175
171
  runBranchPrefix.startsWith(claimPrefix) || claimPrefix.startsWith(runBranchPrefix);
176
172
 
177
173
  const namingProblems = (hum: HumConfig): Problem[] =>
178
- prefixesOverlap(hum) ? [{ problem: "overlapping-prefixes", run: hum.runBranchPrefix, claim: hum.claimPrefix }] : [];
174
+ doPrefixesOverlap(hum) ? [{ problem: "overlapping-prefixes", run: hum.runBranchPrefix, claim: hum.claimPrefix }] : [];
179
175
 
180
176
  const levelNames = (hum: HumConfig): ReadonlySet<string> => new Set(hum.levels.map(({ name }) => name));
181
177
 
182
178
  const ALL_KINDS = "*";
183
179
 
184
180
  /** A path whose level releases only after proof names a proof for every kind, or for each kind there is. */
185
- const provesEveryKind = (rule: PathRule, kinds: readonly string[]): boolean =>
181
+ const doesProveEveryKind = (rule: PathRule, kinds: readonly string[]): boolean =>
186
182
  rule.proofs?.[ALL_KINDS] !== undefined || kinds.every((kind) => rule.proofs?.[kind] !== undefined);
187
183
 
188
184
  const pathProblems = (hum: HumConfig): Problem[] => {
@@ -192,7 +188,7 @@ const pathProblems = (hum: HumConfig): Problem[] => {
192
188
  return [
193
189
  ...[...hum.paths, ...hum.launches, ...Object.values(hum.kindFloors).map((level) => ({ level }))].flatMap(({ level }): Problem[] => (levels.has(level) ? [] : [{ problem: "unknown-level", level }])),
194
190
  ...hum.paths.flatMap((rule): Problem[] =>
195
- afterProof.has(rule.level) && !provesEveryKind(rule, hum.kinds) ? [{ problem: "path-without-proof", glob: rule.glob, level: rule.level }] : [],
191
+ afterProof.has(rule.level) && !doesProveEveryKind(rule, hum.kinds) ? [{ problem: "path-without-proof", glob: rule.glob, level: rule.level }] : [],
196
192
  ),
197
193
  ];
198
194
  };
@@ -9,12 +9,10 @@ const placeholder = createAsyncLogic({ run: async () => {} });
9
9
  * Throws with xstate's message when the machine is illegal.
10
10
  */
11
11
  export const kindMachine = (kind: Kind, sources: Readonly<Record<string, AnyActorLogic>> = {}): AnyStateMachine => {
12
- const actors: Record<string, AnyActorLogic> = {};
13
-
14
- for (const node of Object.values(kind.machine.states)) {
15
- if (node.invoke) actors[node.invoke.src] = sources[node.invoke.src] ?? placeholder;
16
- }
17
-
18
12
  // SAFETY: the zod machine schema is a subset of xstate's MachineJSON, and machineFromJSON validates the rest.
19
- return machineFromJSON(kind.machine as Parameters<typeof machineFromJSON>[0], { actors });
13
+ return machineFromJSON(kind.machine as Parameters<typeof machineFromJSON>[0], { actors: invokedSources(kind, placeholder, sources) });
20
14
  };
15
+
16
+ /** An actor for each source the kind's machine invokes: the one `sources` gives, else `fallback`. */
17
+ export const invokedSources = (kind: Kind, fallback: AnyActorLogic, sources: Readonly<Record<string, AnyActorLogic>> = {}): Record<string, AnyActorLogic> =>
18
+ Object.fromEntries(Object.values(kind.machine.states).flatMap(({ invoke }) => (invoke ? [[invoke.src, sources[invoke.src] ?? fallback]] : [])));
@@ -51,6 +51,13 @@ const DESCRIPTIONS = {
51
51
  // SAFETY: each description is keyed by the problem name it reads, so the lookup by `problem.problem` takes its own variant.
52
52
  export const describeProblem = (problem: Problem): string => (DESCRIPTIONS[problem.problem] as (problem: Problem) => string)(problem);
53
53
 
54
+ /** hum commits as the owner and invents no identity: this names each git config key that holds none, and how to set it. */
55
+ export const noGitIdentity = (missing: readonly string[]): Refusal => ({
56
+ code: "no-git-identity",
57
+ missing,
58
+ message: `hum commits as you, and git config holds no ${missing.join(" or ")}. Set ${missing.length === 1 ? "it" : "each"}, then run again: ${missing.map((key) => `git config --global ${key} "<yours>"`).join("; ")}.`,
59
+ });
60
+
54
61
  export const invalidConfig = (problems: readonly Problem[]): Refusal => ({
55
62
  code: "invalid-config",
56
63
  problems,