@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.
- package/defaults/hum.json +321 -0
- package/defaults/kinds/check.json +183 -0
- package/defaults/kinds/docs.json +151 -0
- package/defaults/kinds/feature.json +202 -0
- package/defaults/kinds/fix.json +183 -0
- package/defaults/kinds/hotfix.json +164 -0
- package/defaults/roles/build.md +3 -0
- package/defaults/roles/fix.md +1 -0
- package/defaults/roles/plan.md +3 -0
- package/defaults/roles/review.md +3 -0
- package/evals/alignment/RESULTS.md +8 -0
- package/evals/alignment/cases.jsonl +128 -0
- package/evals/alignment/sample.jsonl +20 -0
- package/evals/kind/RESULTS.md +5 -0
- package/evals/kind/cases.jsonl +24 -0
- package/evals/plan-outcome/RESULTS.md +4 -0
- package/evals/plan-outcome/cases.jsonl +12 -0
- package/evals/repeat-pair/RESULTS.md +4 -0
- package/evals/repeat-pair/cases.jsonl +51 -0
- package/evals/reply-option/RESULTS.md +3 -0
- package/evals/reply-option/cases.jsonl +45 -0
- package/evals/review-verdict/RESULTS.md +4 -0
- package/evals/review-verdict/cases.jsonl +12 -0
- package/package.json +88 -4
- package/schema/hum.schema.json +1355 -0
- package/scripts/eval.ts +244 -0
- package/src/adapter-api.ts +134 -0
- package/src/adapters/admit.ts +111 -0
- package/src/adapters/argument.ts +11 -0
- package/src/adapters/claim.ts +93 -0
- package/src/adapters/claude-bg.ts +375 -0
- package/src/adapters/claude-p.ts +593 -0
- package/src/adapters/contract.ts +231 -0
- package/src/adapters/fake.ts +157 -0
- package/src/adapters/git.ts +155 -0
- package/src/adapters/github.ts +457 -0
- package/src/adapters/guard.ts +152 -0
- package/src/adapters/history.ts +215 -0
- package/src/adapters/item-file.ts +102 -0
- package/src/adapters/limit.ts +67 -0
- package/src/adapters/markdown.ts +365 -0
- package/src/adapters/marked.ts +119 -0
- package/src/adapters/model-call.ts +75 -0
- package/src/adapters/once.ts +45 -0
- package/src/adapters/owner-commit.ts +60 -0
- package/src/adapters/pull-requests.ts +253 -0
- package/src/adapters/registry.ts +156 -0
- package/src/adapters/roundup.ts +291 -0
- package/src/adapters/serial.ts +22 -0
- package/src/adapters/transcript.ts +99 -0
- package/src/cli/commands.ts +46 -0
- package/src/cli/main.ts +8 -0
- package/src/cli/ops.ts +224 -0
- package/src/cli/service.ts +156 -0
- package/src/cli/setup.ts +141 -0
- package/src/cli/shared-watch.ts +127 -0
- package/src/config/change.ts +54 -0
- package/src/config/checks.ts +217 -0
- package/src/config/git-ref-name.d.ts +3 -0
- package/src/config/hash.ts +6 -0
- package/src/config/json.ts +6 -0
- package/src/config/load.ts +88 -0
- package/src/config/machine.ts +20 -0
- package/src/config/migrate.ts +61 -0
- package/src/config/refusal.ts +58 -0
- package/src/config/schema.ts +465 -0
- package/src/config/settings.ts +6 -0
- package/src/config/state-map.ts +76 -0
- package/src/decide/alignment.ts +79 -0
- package/src/decide/answer.ts +131 -0
- package/src/decide/kind.ts +39 -0
- package/src/decide/labels.ts +137 -0
- package/src/decide/merge.ts +102 -0
- package/src/decide/prose.ts +109 -0
- package/src/decide/question.ts +159 -0
- package/src/decide/review.ts +10 -0
- package/src/decide/risk.ts +216 -0
- package/src/decide/taste.ts +37 -0
- package/src/exec.ts +80 -0
- package/src/index.ts +200 -0
- package/src/loop/breaks.ts +8 -0
- package/src/loop/check-item.ts +76 -0
- package/src/loop/ci.ts +8 -0
- package/src/loop/github.ts +81 -0
- package/src/loop/groups.ts +108 -0
- package/src/loop/memory.ts +70 -0
- package/src/loop/notes.ts +76 -0
- package/src/loop/pair.ts +39 -0
- package/src/loop/pass.ts +99 -0
- package/src/loop/proof.ts +85 -0
- package/src/loop/prove-item.ts +33 -0
- package/src/loop/records.ts +75 -0
- package/src/loop/signals.ts +130 -0
- package/src/measure/inputs.ts +28 -0
- package/src/measure/measure.ts +68 -0
- package/src/service/cards.ts +24 -0
- package/src/service/ci-tick.ts +28 -0
- package/src/service/launchd.ts +16 -0
- package/src/service/supervise.ts +145 -0
- package/src/service/systemd.ts +44 -0
- package/src/service/token.ts +21 -0
- package/src/service/unit.ts +29 -0
- package/src/service/wake.ts +30 -0
- package/src/service/workflows.ts +97 -0
- package/src/setup/propose.ts +120 -0
- package/src/setup/prove.ts +216 -0
- package/src/setup/scan.ts +186 -0
- package/src/setup/scratch.ts +81 -0
- package/src/setup/shipped.ts +15 -0
- package/src/setup/tables.ts +101 -0
- package/src/setup/waits.ts +58 -0
- package/src/setup/write.ts +161 -0
- package/src/slots/env.ts +42 -0
- package/src/slots/pool.ts +329 -0
- package/src/slots/scan.ts +26 -0
- package/src/slots/worktree.ts +17 -0
- package/src/state/events.ts +52 -0
- package/src/state/faults.ts +73 -0
- package/src/state/format.ts +50 -0
- package/src/state/fs.ts +100 -0
- package/src/state/items.ts +189 -0
- package/src/state/open.ts +80 -0
- package/src/state/ops.ts +76 -0
- package/src/state/records.ts +35 -0
- package/src/state/runs.ts +99 -0
- package/src/state/saved.ts +119 -0
- package/src/status/file.ts +49 -0
- package/src/status/format.ts +132 -0
- package/src/status/sections.ts +14 -0
- package/src/status/version.ts +2 -0
- package/src/time.ts +7 -0
- package/src/worker/alignment-report.ts +18 -0
- package/src/worker/answers.ts +153 -0
- package/src/worker/base-check.ts +46 -0
- package/src/worker/checks.ts +26 -0
- package/src/worker/kind.ts +68 -0
- package/src/worker/land.ts +508 -0
- package/src/worker/lifecycle.ts +97 -0
- package/src/worker/merged.ts +29 -0
- package/src/worker/open.ts +100 -0
- package/src/worker/prose-run.ts +56 -0
- package/src/worker/questions.ts +89 -0
- package/src/worker/scheduler.ts +135 -0
- package/src/worker/signature.ts +41 -0
- package/src/worker/tally.ts +25 -0
- package/src/worker/taste.ts +38 -0
- package/src/worker/thin-path.ts +886 -0
- package/src/worker/worker.ts +728 -0
- package/surface.json +8787 -0
- package/README.md +0 -3
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import PQueue from "p-queue";
|
|
2
|
+
import type { Adapter } from "../adapter-api.ts";
|
|
3
|
+
|
|
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);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Runs an adapter's calls one at a time. Runs that go side by side share one adapter, and an adapter
|
|
10
|
+
* that keeps a clone, as the markdown source does, must not take two writes into it at once.
|
|
11
|
+
*/
|
|
12
|
+
export const serialized = (adapter: Adapter): Adapter => {
|
|
13
|
+
const queue = new PQueue({ concurrency: 1 });
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
apiVersion: adapter.apiVersion,
|
|
17
|
+
workSource: inOrder(adapter.workSource, queue),
|
|
18
|
+
questions: inOrder(adapter.questions, queue),
|
|
19
|
+
answers: inOrder(adapter.answers, queue),
|
|
20
|
+
release: inOrder(adapter.release, queue),
|
|
21
|
+
};
|
|
22
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { epochMs } from "./limit.ts";
|
|
3
|
+
|
|
4
|
+
/** Tokens a run adds to the item's bill: input, output and cache writes. Cache reads are not counted. */
|
|
5
|
+
export const billed = (input: number, output: number, cacheWrite: number): number => input + output + cacheWrite;
|
|
6
|
+
|
|
7
|
+
const Counts = {
|
|
8
|
+
input_tokens: z.number().default(0),
|
|
9
|
+
output_tokens: z.number().default(0),
|
|
10
|
+
cache_creation_input_tokens: z.number().default(0),
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** The advisor model's own calls ride in the message's `iterations`; the message's top-level counts leave them out. */
|
|
14
|
+
const ADVISOR_ITERATION = "advisor_message";
|
|
15
|
+
|
|
16
|
+
const Usage = z.looseObject({
|
|
17
|
+
...Counts,
|
|
18
|
+
cache_read_input_tokens: z.number().default(0),
|
|
19
|
+
iterations: z.array(z.looseObject({ type: z.string(), ...Counts })).default([]),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
type Usage = z.infer<typeof Usage>;
|
|
23
|
+
|
|
24
|
+
const advisorTokens = ({ iterations }: Usage): number =>
|
|
25
|
+
iterations.filter(({ type }) => type === ADVISOR_ITERATION).reduce((sum, call) => sum + billed(call.input_tokens, call.output_tokens, call.cache_creation_input_tokens), 0);
|
|
26
|
+
|
|
27
|
+
/** The rows of a transcript that matter, each named by what it is. Any other row says nothing. */
|
|
28
|
+
const Row = z.union([
|
|
29
|
+
z
|
|
30
|
+
.looseObject({
|
|
31
|
+
type: z.literal("assistant"),
|
|
32
|
+
isApiErrorMessage: z.literal(true),
|
|
33
|
+
error: z.literal("rate_limit"),
|
|
34
|
+
quotaLimits: z.looseObject({ resetsAt: z.number().optional() }).optional(),
|
|
35
|
+
message: z.looseObject({ content: z.array(z.looseObject({ text: z.string().optional() })).default([]) }).optional(),
|
|
36
|
+
})
|
|
37
|
+
.transform(({ quotaLimits, message }) => ({ kind: "limit", text: message?.content.map(({ text }) => text ?? "").join(" ").trim() ?? "", resetsAt: quotaLimits?.resetsAt === undefined ? undefined : epochMs(quotaLimits.resetsAt) }) as const),
|
|
38
|
+
z
|
|
39
|
+
.looseObject({ type: z.literal("assistant"), isApiErrorMessage: z.literal(true), error: z.string().default("api error") })
|
|
40
|
+
.transform(({ error }) => ({ kind: "api-error", error }) as const),
|
|
41
|
+
z
|
|
42
|
+
.looseObject({ type: z.literal("assistant"), message: z.looseObject({ id: z.string(), model: z.string().optional(), usage: Usage }) })
|
|
43
|
+
.transform(({ message: { id, model, usage } }) => ({ kind: "message", id, spent: { billed: billed(usage.input_tokens, usage.output_tokens, usage.cache_creation_input_tokens) + advisorTokens(usage), output: usage.output_tokens, cacheRead: usage.cache_read_input_tokens, model } }) as const),
|
|
44
|
+
z
|
|
45
|
+
.looseObject({ type: z.literal("attachment"), timestamp: z.iso.datetime(), attachment: z.looseObject({ type: z.literal("structured_output"), data: z.unknown() }) })
|
|
46
|
+
.transform(({ timestamp, attachment }) => ({ kind: "structured", data: attachment.data, at: Date.parse(timestamp) }) as const),
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
type Row = z.infer<typeof Row>;
|
|
50
|
+
|
|
51
|
+
/** What one message cost. A message streams as several rows that each repeat its final usage, so cost is kept by message id. */
|
|
52
|
+
type Spent = { readonly billed: number; readonly output: number; readonly cacheRead: number; readonly model: string | undefined };
|
|
53
|
+
|
|
54
|
+
/** What a background run's transcript says so far. */
|
|
55
|
+
export type RunTranscript = {
|
|
56
|
+
readonly messages: Readonly<Record<string, Spent>>;
|
|
57
|
+
/** The structured result and the epoch ms it was written. */
|
|
58
|
+
readonly structured: { readonly data: unknown; readonly at: number } | undefined;
|
|
59
|
+
/** The API's error, when the run ended on one. */
|
|
60
|
+
readonly apiError: string | undefined;
|
|
61
|
+
/** The usage limit the run ran into: the reset time as epoch ms when the row carries one, and the row's own words. */
|
|
62
|
+
readonly limit: { readonly resetsAt: number | undefined; readonly text: string } | undefined;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** A line that is no JSON, such as a last row still being written, says nothing. */
|
|
66
|
+
const parseRow = (line: string): Row | undefined => {
|
|
67
|
+
try {
|
|
68
|
+
return Row.safeParse(JSON.parse(line)).data;
|
|
69
|
+
} catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
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;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const EMPTY: RunTranscript = { messages: {}, structured: undefined, apiError: undefined, limit: undefined };
|
|
85
|
+
|
|
86
|
+
/** Reads a run's transcript file. Tokens are summed over distinct message ids, as `-p` sums its `modelUsage`. */
|
|
87
|
+
export const readTranscript = (jsonl: string): RunTranscript => jsonl.split("\n").filter(Boolean).reduce((t, line) => readRow(t, parseRow(line)), EMPTY);
|
|
88
|
+
|
|
89
|
+
const sumOf = (t: RunTranscript, field: (spent: Spent) => number): number => Object.values(t.messages).reduce((sum, spent) => sum + field(spent), 0);
|
|
90
|
+
|
|
91
|
+
export const billedTokens = (t: RunTranscript): number => sumOf(t, (spent) => spent.billed);
|
|
92
|
+
|
|
93
|
+
/** Output tokens the transcript holds, which the job's own count is compared with. */
|
|
94
|
+
export const outputTokens = (t: RunTranscript): number => sumOf(t, (spent) => spent.output);
|
|
95
|
+
|
|
96
|
+
export const cacheReadTokens = (t: RunTranscript): number => sumOf(t, (spent) => spent.cacheRead);
|
|
97
|
+
|
|
98
|
+
/** The model ids that answered, each once. */
|
|
99
|
+
export const modelsOf = (t: RunTranscript): string[] => [...new Set(Object.values(t.messages).flatMap(({ model }) => (model === undefined ? [] : [model])))];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { InvalidArgumentError } from "commander";
|
|
2
|
+
|
|
3
|
+
/** One flag of an op: its commander spelling, whether it may repeat, and how its value is read. */
|
|
4
|
+
export type Flag = { readonly flag: string; readonly repeats?: true; readonly parse?: (value: string) => number };
|
|
5
|
+
|
|
6
|
+
const wholeSeconds = (value: string): number => {
|
|
7
|
+
const seconds = Number(value);
|
|
8
|
+
|
|
9
|
+
if (!Number.isInteger(seconds) || seconds <= 0) throw new InvalidArgumentError("a positive whole number of seconds");
|
|
10
|
+
|
|
11
|
+
return seconds;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
type Spec = { readonly summary: string; readonly args: string; readonly flags?: readonly Flag[] };
|
|
15
|
+
|
|
16
|
+
/** One `hum <op>`, as `hum help --json` prints it. */
|
|
17
|
+
export type Command = { readonly summary: string; readonly usage: string };
|
|
18
|
+
|
|
19
|
+
const specs = {
|
|
20
|
+
"list-ready": { summary: "List the items ready to claim.", args: "" },
|
|
21
|
+
claim: { summary: "Take an item for a holder; the first caller wins and a claim expires unless renewed.", args: "<item> <holder>", flags: [{ flag: "--ttl <seconds>", parse: wholeSeconds }, { flag: "--renew" }] },
|
|
22
|
+
read: { summary: "Print an item with its thread.", args: "<item>" },
|
|
23
|
+
comment: { summary: "Add a comment to an item's thread.", args: "<item> <text...>" },
|
|
24
|
+
ask: { summary: "Put a question to the owner on an item's thread.", args: "<item> <text...>", flags: [{ flag: "--option <word>", repeats: true }] },
|
|
25
|
+
answer: { summary: "Write the owner's answer into the item, commit it and push it with hooks off.", args: "<item> <text...>", flags: [{ flag: "--option <word>" }] },
|
|
26
|
+
watch: { summary: "Say whether anything changed since the last watch; costs no rate limit when idle.", args: "", flags: [{ flag: "--since <token>" }] },
|
|
27
|
+
"file-follow-up": { summary: "File a ready item from another item; the same title from the same item files once.", args: "<from-item> <title>", flags: [{ flag: "--body <text>" }] },
|
|
28
|
+
decide: { summary: "Record a choice made without the owner.", args: "<item> <text...>" },
|
|
29
|
+
publish: { summary: "Publish an item's artifact through the release integration.", args: "<item> <ref>" },
|
|
30
|
+
release: { summary: "Release a published artifact through the release integration.", args: "<item> <ref>" },
|
|
31
|
+
push: { summary: "Run git push with hooks off; every argument goes to git.", args: "[git push args...]" },
|
|
32
|
+
} as const satisfies Record<string, Spec>;
|
|
33
|
+
|
|
34
|
+
export type OpName = keyof typeof specs;
|
|
35
|
+
|
|
36
|
+
/** What commander registers for each op: the one place an op's arguments and flags are written. */
|
|
37
|
+
export const opSpecs: Readonly<Record<OpName, Spec>> = specs;
|
|
38
|
+
|
|
39
|
+
const usageOf = (name: string, { args, flags = [] }: Spec): string =>
|
|
40
|
+
["hum", name, args, ...flags.map(({ flag, repeats }) => `[${flag}]${repeats ? "..." : ""}`)].filter(Boolean).join(" ");
|
|
41
|
+
|
|
42
|
+
/** Every `hum <op>`, keyed by its name. Roles and machines name only these. */
|
|
43
|
+
// SAFETY: the entries are the keys of `specs`, mapped one to one.
|
|
44
|
+
export const commands = Object.fromEntries(
|
|
45
|
+
Object.entries(opSpecs).map(([name, spec]) => [name, { summary: spec.summary, usage: usageOf(name, spec) }]),
|
|
46
|
+
) as Readonly<Record<OpName, Command>>;
|
package/src/cli/main.ts
ADDED
package/src/cli/ops.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { Command, CommanderError, Option } from "commander";
|
|
2
|
+
import { x } from "tinyexec";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { type ClaimResult, type Item, type ItemRef, PermanentError, Watch } from "../adapter-api.ts";
|
|
5
|
+
import { pushArgs } from "../adapters/git.ts";
|
|
6
|
+
import { resolveAdapters, type Slot } from "../adapters/registry.ts";
|
|
7
|
+
import { readSettings } from "../config/settings.ts";
|
|
8
|
+
import { HumConfig } from "../config/schema.ts";
|
|
9
|
+
import { dropInto } from "../state/fs.ts";
|
|
10
|
+
import { defaultStateDir, openState } from "../state/open.ts";
|
|
11
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
12
|
+
import { type OpName, commands, type Flag, opSpecs } from "./commands.ts";
|
|
13
|
+
import { addServiceCommands } from "./service.ts";
|
|
14
|
+
import { addSetupCommands } from "./setup.ts";
|
|
15
|
+
import { sharedWatch } from "./shared-watch.ts";
|
|
16
|
+
import { SECOND_MS } from "../time.ts";
|
|
17
|
+
|
|
18
|
+
type Printable = ItemRef[] | ItemRef | Item | ClaimResult | Watch | { readonly ok: true };
|
|
19
|
+
|
|
20
|
+
export type Io = {
|
|
21
|
+
readonly cwd: string;
|
|
22
|
+
readonly stdout: (text: string) => void;
|
|
23
|
+
readonly stderr: (text: string) => void;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const EXIT_FAILED = 1;
|
|
27
|
+
const EXIT_MISUSED = 2;
|
|
28
|
+
|
|
29
|
+
const OK = { ok: true } as const;
|
|
30
|
+
|
|
31
|
+
const CliSettings = z.looseObject({
|
|
32
|
+
claimExpirySeconds: HumConfig.shape.claimExpirySeconds,
|
|
33
|
+
watchCacheSeconds: HumConfig.shape.watchCacheSeconds,
|
|
34
|
+
watchLockSeconds: HumConfig.shape.watchLockSeconds,
|
|
35
|
+
runPlaces: HumConfig.shape.runPlaces,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
type CliSettings = z.infer<typeof CliSettings>;
|
|
39
|
+
|
|
40
|
+
type Flags = { ttl?: number; renew?: boolean; option?: string | string[]; since?: string; body?: string };
|
|
41
|
+
|
|
42
|
+
type Adapters = Awaited<ReturnType<typeof resolveAdapters>>;
|
|
43
|
+
|
|
44
|
+
/** What every op reads: its positional arguments, flags and the integrations `hum.json` names. */
|
|
45
|
+
type Call = {
|
|
46
|
+
/** The first positional argument. */
|
|
47
|
+
readonly item: string;
|
|
48
|
+
/** The second positional argument. */
|
|
49
|
+
readonly second: string;
|
|
50
|
+
/** Every positional argument after the first, as one text. */
|
|
51
|
+
readonly text: string;
|
|
52
|
+
readonly flags: Flags;
|
|
53
|
+
readonly options: readonly string[];
|
|
54
|
+
readonly stateDir: string;
|
|
55
|
+
/** The folder the worker reads item ids from at once. */
|
|
56
|
+
readonly inbox: string;
|
|
57
|
+
readonly settings: CliSettings;
|
|
58
|
+
/** The integration role of a slot; throws when none is set up. */
|
|
59
|
+
readonly slot: <T>(name: Slot, role: (adapter: NonNullable<Adapters[Slot]>) => T | undefined) => T;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** Leaves a wake file in the inbox for the worker on this machine. A repo that runs only in CI has no such worker to read it, so no file is left. */
|
|
63
|
+
const wakeWorker = ({ inbox, settings }: Pick<Call, "inbox" | "settings">, item: string): void => {
|
|
64
|
+
if (settings.runPlaces.includes("mac")) dropInto(inbox, item);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const performed = async (action: Promise<void>): Promise<Printable> => {
|
|
68
|
+
await action;
|
|
69
|
+
|
|
70
|
+
return OK;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type Handler = (call: Call) => Promise<Printable>;
|
|
74
|
+
|
|
75
|
+
const handlers = {
|
|
76
|
+
"list-ready": ({ slot }) => slot("work-source", (a) => a.workSource).listReady(),
|
|
77
|
+
claim: ({ slot, item, second: holder, flags, settings }) => {
|
|
78
|
+
const source = slot("work-source", (a) => a.workSource);
|
|
79
|
+
const ttlMs = (flags.ttl ?? settings.claimExpirySeconds) * SECOND_MS;
|
|
80
|
+
|
|
81
|
+
return (flags.renew ? source.renew : source.claim)(item, holder, ttlMs);
|
|
82
|
+
},
|
|
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 })),
|
|
86
|
+
answer: async ({ slot, item, text, options, inbox, settings }) => {
|
|
87
|
+
await slot("answers", (a) => a.answers).answer(item, { text, option: options[0] });
|
|
88
|
+
wakeWorker({ inbox, settings }, item);
|
|
89
|
+
|
|
90
|
+
return OK;
|
|
91
|
+
},
|
|
92
|
+
watch: ({ slot, stateDir, inbox, flags, settings }) => {
|
|
93
|
+
const answers = slot("answers", (a) => a.answers);
|
|
94
|
+
|
|
95
|
+
if (flags.since !== undefined) return answers.watch(flags.since).then((found) => Watch.parse(found));
|
|
96
|
+
|
|
97
|
+
return sharedWatch({
|
|
98
|
+
stateDir,
|
|
99
|
+
now: Date.now,
|
|
100
|
+
cacheMs: settings.watchCacheSeconds * SECOND_MS,
|
|
101
|
+
lockMs: settings.watchLockSeconds * SECOND_MS,
|
|
102
|
+
read: async (since) => Watch.parse(await answers.watch(since)),
|
|
103
|
+
changed: () => wakeWorker({ inbox, settings }, ""),
|
|
104
|
+
});
|
|
105
|
+
},
|
|
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)),
|
|
110
|
+
} as const satisfies Record<Exclude<OpName, "push">, Handler>;
|
|
111
|
+
|
|
112
|
+
const callOf = async (positionals: readonly string[], flags: Flags, io: Io): Promise<Call> => {
|
|
113
|
+
const stateDir = await defaultStateDir(io.cwd);
|
|
114
|
+
const state = openState(stateDir);
|
|
115
|
+
const settings = readSettings(io.cwd, CliSettings);
|
|
116
|
+
|
|
117
|
+
const adapters = await resolveAdapters(io.cwd, {
|
|
118
|
+
faults: state.faults,
|
|
119
|
+
guard: {},
|
|
120
|
+
context: { report: (fault) => void state.faults.raise(fault), now: Date.now },
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const [item = "", ...rest] = positionals;
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
item,
|
|
127
|
+
second: rest[0] ?? "",
|
|
128
|
+
text: rest.join(" "),
|
|
129
|
+
flags,
|
|
130
|
+
options: [flags.option ?? []].flat(),
|
|
131
|
+
stateDir,
|
|
132
|
+
inbox: state.inbox,
|
|
133
|
+
settings,
|
|
134
|
+
slot: (name, role) => {
|
|
135
|
+
const adapter = adapters[name];
|
|
136
|
+
const found = adapter && role(adapter);
|
|
137
|
+
|
|
138
|
+
if (!found) throw new PermanentError(`no ${name} integration is set up; name one under "integrations" in .hum/hum.json`);
|
|
139
|
+
|
|
140
|
+
return found;
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** Runs one parsed `hum <op>` and returns its exit code: 0 done, 1 failed, 2 misused. */
|
|
146
|
+
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;
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
const printed = await handlers[op](await callOf(positionals, flags, io));
|
|
151
|
+
|
|
152
|
+
io.stdout(`${JSON.stringify(printed)}\n`);
|
|
153
|
+
|
|
154
|
+
return 0;
|
|
155
|
+
} catch (error) {
|
|
156
|
+
io.stderr(`hum ${op}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
157
|
+
|
|
158
|
+
return EXIT_FAILED;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const optionOf = ({ flag, repeats, parse }: Flag): Option => {
|
|
163
|
+
const option = new Option(flag);
|
|
164
|
+
|
|
165
|
+
if (repeats) return option.default([]).argParser((word: string, seen: string[]) => [...seen, word]);
|
|
166
|
+
|
|
167
|
+
return parse ? option.argParser(parse) : option;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** The `hum` command tree. Each command reports its exit code through `exitWith`. */
|
|
171
|
+
export const buildProgram = (io: Io, exitWith: (code: number) => void): Command => {
|
|
172
|
+
const root = new Command("hum")
|
|
173
|
+
.version(pkg.version)
|
|
174
|
+
.enablePositionalOptions()
|
|
175
|
+
.showHelpAfterError()
|
|
176
|
+
.exitOverride()
|
|
177
|
+
.configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
|
|
178
|
+
|
|
179
|
+
// SAFETY: `opSpecs` is a record keyed by `OpName`, so its entries are `OpName` pairs.
|
|
180
|
+
for (const [name, spec] of Object.entries(opSpecs) as [OpName, (typeof opSpecs)[OpName]][]) {
|
|
181
|
+
const op = root.command(`${name} ${spec.args}`).description(spec.summary);
|
|
182
|
+
|
|
183
|
+
for (const flag of spec.flags ?? []) op.addOption(optionOf(flag));
|
|
184
|
+
|
|
185
|
+
if (name === "push") op.allowUnknownOption().allowExcessArguments().helpOption(false);
|
|
186
|
+
|
|
187
|
+
op.action(async () => {
|
|
188
|
+
exitWith(await perform(name, op.processedArgs.flat(), op.opts(), io));
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
root.command("help").description("Print every op's usage; --json prints the table roles read.").option("--json").action((flags: { json?: boolean }) => {
|
|
193
|
+
io.stdout(`${flags.json ? JSON.stringify(commands) : Object.values(commands).map((c) => c.usage).join("\n")}\n`);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
addServiceCommands(root, io, exitWith);
|
|
197
|
+
addSetupCommands(root, io, exitWith);
|
|
198
|
+
|
|
199
|
+
return root;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/** Runs `hum <argv>` (an op and its arguments) and returns its exit code: 0 done, 1 failed, 2 misused. */
|
|
203
|
+
export const runCli = async (argv: readonly string[], io: Io): Promise<number> => {
|
|
204
|
+
let code = 0;
|
|
205
|
+
|
|
206
|
+
const root = buildProgram(io, (exit) => {
|
|
207
|
+
code = exit;
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
try {
|
|
211
|
+
await root.parseAsync([...argv], { from: "user" });
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (error instanceof CommanderError) return error.exitCode === 0 ? 0 : EXIT_MISUSED;
|
|
214
|
+
|
|
215
|
+
io.stderr(`hum ${argv[0] ?? ""}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
216
|
+
|
|
217
|
+
return EXIT_FAILED;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return code;
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
/** Runs one `hum <op>` and returns its exit code: 0 done, 1 failed, 2 misused. */
|
|
224
|
+
export const runOp = (op: OpName, argv: readonly string[], io: Io): Promise<number> => runCli([op, ...argv], io);
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Command } from "commander";
|
|
4
|
+
import { x } from "tinyexec";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { listHopeSkills } from "../config/load.ts";
|
|
7
|
+
import { HumConfig } from "../config/schema.ts";
|
|
8
|
+
import { readSettings } from "../config/settings.ts";
|
|
9
|
+
import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
|
|
10
|
+
import { readCiTick, recordCiTick } from "../service/ci-tick.ts";
|
|
11
|
+
import { EXIT_UPDATED, supervise } from "../service/supervise.ts";
|
|
12
|
+
import { reportCards, wakeUntilQuiet } from "../service/wake.ts";
|
|
13
|
+
import { defaultStateDir, openState } from "../state/open.ts";
|
|
14
|
+
import { SECOND_MS } from "../time.ts";
|
|
15
|
+
import { readStatus } from "../status/file.ts";
|
|
16
|
+
import { npmLatest, openWorker } from "../worker/open.ts";
|
|
17
|
+
import type { Io } from "./ops.ts";
|
|
18
|
+
|
|
19
|
+
const EXIT_OK = 0;
|
|
20
|
+
|
|
21
|
+
/** The start script's exit code when it gave up or was stopped: the unit restarts a script only after a failure. */
|
|
22
|
+
const EXIT_STAY_DOWN = EXIT_OK;
|
|
23
|
+
|
|
24
|
+
const EXIT_CARDS_SHOWN = 1;
|
|
25
|
+
|
|
26
|
+
const SCHEDULE_EVENT = "schedule";
|
|
27
|
+
|
|
28
|
+
type WorkFlags = { holder?: string; base?: string };
|
|
29
|
+
|
|
30
|
+
/** What a worker needs to know that no file in the repo says: who it claims as, and where items merge. */
|
|
31
|
+
const withWorkOptions = (cmd: Command): Command =>
|
|
32
|
+
cmd
|
|
33
|
+
.option("--holder <name>", "the name this worker claims items by; default <where>@<host>")
|
|
34
|
+
.option("--base <branch>", "the branch items merge into; default main");
|
|
35
|
+
|
|
36
|
+
const PluginList = z.array(z.looseObject({ id: z.string(), installPath: z.string() }));
|
|
37
|
+
|
|
38
|
+
/** The folder of the installed hope plugin: `HUM_HOPE_ROOT`, else the path `claude plugin list` gives. */
|
|
39
|
+
export const hopeRoot = async (): Promise<string> => {
|
|
40
|
+
if (process.env.HUM_HOPE_ROOT) return process.env.HUM_HOPE_ROOT;
|
|
41
|
+
|
|
42
|
+
const listed = await exec("claude", ["plugin", "list", "--json"], { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
|
|
43
|
+
const hope = listed.exitCode === 0 ? PluginList.parse(JSON.parse(listed.stdout)).find((plugin) => plugin.id.startsWith("hope@")) : undefined;
|
|
44
|
+
|
|
45
|
+
if (!hope) throw new Error("the hope plugin is not installed: run `claude plugin install hope@moo.md`, or set HUM_HOPE_ROOT to its folder");
|
|
46
|
+
|
|
47
|
+
return hope.installPath;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const ServiceSettings = z.looseObject({
|
|
51
|
+
tickIntervalSeconds: HumConfig.shape.tickIntervalSeconds,
|
|
52
|
+
workerDownTicks: HumConfig.shape.workerDownTicks,
|
|
53
|
+
maxCrashes: HumConfig.shape.maxCrashes,
|
|
54
|
+
crashWindowSeconds: HumConfig.shape.crashWindowSeconds,
|
|
55
|
+
restartBackoff: HumConfig.shape.restartBackoff,
|
|
56
|
+
commandTimeoutSeconds: HumConfig.shape.commandTimeoutSeconds,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The settings the start script needs, with the shipped default for any it cannot read. A config the worker
|
|
61
|
+
* refuses is the worker's to report: it exits, and the script counts the crash and shows the card.
|
|
62
|
+
*/
|
|
63
|
+
const serviceSettings = (repo: string): z.infer<typeof ServiceSettings> => {
|
|
64
|
+
try {
|
|
65
|
+
return readSettings(repo, ServiceSettings);
|
|
66
|
+
} catch {
|
|
67
|
+
return ServiceSettings.parse({});
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** 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") => {
|
|
73
|
+
const timeoutMs = commandTimeoutMs(serviceSettings(repo));
|
|
74
|
+
|
|
75
|
+
return openWorker(repo, {
|
|
76
|
+
hopeSkills: listHopeSkills(await hopeRoot()),
|
|
77
|
+
holder: flags.holder ?? `${where}@${hostname()}`,
|
|
78
|
+
base: flags.base,
|
|
79
|
+
where,
|
|
80
|
+
latestVersion: where === "mac" ? npmLatest : undefined,
|
|
81
|
+
ciTick: where === "mac" ? () => readCiTick(repo, "origin", timeoutMs) : undefined,
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const onStop = (stop: () => void) => {
|
|
86
|
+
for (const signal of ["SIGTERM", "SIGINT"] as const) process.once(signal, stop);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** `hum work` as a child process of this one, sharing its terminal. */
|
|
90
|
+
const spawnWorker = (cwd: string, workArgs: readonly string[]) => {
|
|
91
|
+
const child = x(process.execPath, [process.argv[1] ?? "", "work", ...workArgs], { nodeOptions: { cwd, stdio: "inherit" } });
|
|
92
|
+
|
|
93
|
+
return { exited: Promise.resolve(child).then(({ exitCode }) => exitCode ?? 1), kill: () => void child.kill("SIGTERM") };
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* `hum work`, `hum serve` and `hum wake`: the processes a service unit and a CI workflow start. They are not ops:
|
|
98
|
+
* roles and machines never name them, so they stay out of the table `hum help --json` prints.
|
|
99
|
+
*/
|
|
100
|
+
export const addServiceCommands = (root: Command, io: Io, done: (code: number) => void): void => {
|
|
101
|
+
withWorkOptions(root.command("work").description("Run the worker on this machine until it is stopped or an update arrives; exits 75 for an update."))
|
|
102
|
+
.action(async (flags: WorkFlags) => {
|
|
103
|
+
const abort = new AbortController();
|
|
104
|
+
|
|
105
|
+
onStop(() => abort.abort());
|
|
106
|
+
|
|
107
|
+
const worker = await openFor(io.cwd, flags, "mac");
|
|
108
|
+
const ended = await worker.serve(abort.signal);
|
|
109
|
+
|
|
110
|
+
io.stderr(`hum work: stopped, ${ended.reason}\n`);
|
|
111
|
+
done(ended.reason === "stopped" ? EXIT_OK : EXIT_UPDATED);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
root
|
|
115
|
+
.command("serve")
|
|
116
|
+
.description("The service unit's start script: run `hum work` with the arguments after `--`, start it again when it exits, and stop after too many crashes.")
|
|
117
|
+
.argument("[work-args...]", "options of `hum work`, after `--`")
|
|
118
|
+
.action(async (workArgs: string[]) => {
|
|
119
|
+
const abort = new AbortController();
|
|
120
|
+
const settings = serviceSettings(io.cwd);
|
|
121
|
+
|
|
122
|
+
onStop(() => abort.abort());
|
|
123
|
+
|
|
124
|
+
const ended = await supervise({
|
|
125
|
+
state: openState(await defaultStateDir(io.cwd)),
|
|
126
|
+
spawn: () => spawnWorker(io.cwd, workArgs),
|
|
127
|
+
now: Date.now,
|
|
128
|
+
intervalMs: settings.tickIntervalSeconds * SECOND_MS,
|
|
129
|
+
workerDownTicks: settings.workerDownTicks,
|
|
130
|
+
maxCrashes: settings.maxCrashes,
|
|
131
|
+
crashWindowMs: settings.crashWindowSeconds * SECOND_MS,
|
|
132
|
+
backoffMs: settings.restartBackoff.firstSeconds * SECOND_MS,
|
|
133
|
+
maxBackoffMs: settings.restartBackoff.maxSeconds * SECOND_MS,
|
|
134
|
+
stop: abort.signal,
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
io.stderr(`hum serve: ${ended}\n`);
|
|
138
|
+
done(EXIT_STAY_DOWN);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
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
|
+
.option("--event <name>", "the GitHub event that started this job")
|
|
143
|
+
.action(async (flags: WorkFlags & { event?: string }) => {
|
|
144
|
+
const worker = await openFor(io.cwd, flags, "ci");
|
|
145
|
+
|
|
146
|
+
await wakeUntilQuiet(worker);
|
|
147
|
+
|
|
148
|
+
if (flags.event === SCHEDULE_EVENT) await recordCiTick(io.cwd, "origin", Date.now(), worker.config.hum.commitIdentity, commandTimeoutMs(worker.config.hum));
|
|
149
|
+
|
|
150
|
+
const status = readStatus(join(await defaultStateDir(io.cwd), "status.json"));
|
|
151
|
+
const cards = status.ok ? status.status.cards : [];
|
|
152
|
+
|
|
153
|
+
await reportCards(cards);
|
|
154
|
+
done(cards.length > 0 ? EXIT_CARDS_SHOWN : EXIT_OK);
|
|
155
|
+
});
|
|
156
|
+
};
|