@moo.md/hum 0.0.0-stage → 0.1.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 +392 -0
- package/src/adapters/claude-p.ts +599 -0
- package/src/adapters/contract.ts +231 -0
- package/src/adapters/fake.ts +157 -0
- package/src/adapters/git.ts +156 -0
- package/src/adapters/github.ts +479 -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 +127 -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 +293 -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 +85 -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 +195 -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 +45 -0
- package/src/worker/checks.ts +40 -0
- package/src/worker/kind.ts +68 -0
- package/src/worker/land.ts +509 -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 +750 -0
- package/surface.json +8787 -0
- package/README.md +0 -3
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
import type { ModelCall } from "../adapters/model-call.ts";
|
|
2
|
+
import { mkdirSync, readFileSync, rmSync, watch } from "node:fs";
|
|
3
|
+
import ExpiryMap from "expiry-map";
|
|
4
|
+
import pMemoize from "p-memoize";
|
|
5
|
+
import PQueue from "p-queue";
|
|
6
|
+
import pTimeout from "p-timeout";
|
|
7
|
+
import { createAsyncLogic } from "xstate";
|
|
8
|
+
import { ADAPTER_API_VERSION, type Answers, type ItemRef, type Questions, type WorkSource } from "../adapter-api.ts";
|
|
9
|
+
import type { Runner } from "../adapters/claude-p.ts";
|
|
10
|
+
import type { Config } from "../config/load.ts";
|
|
11
|
+
import { type Kind, SCHEMA_VERSION } from "../config/schema.ts";
|
|
12
|
+
import { checkTokenAge } from "../service/token.ts";
|
|
13
|
+
import { listFiles } from "../state/fs.ts";
|
|
14
|
+
import { ENGINE_VERSION } from "../state/format.ts";
|
|
15
|
+
import { persistedSnapshot, type SavedSnapshot } from "../state/items.ts";
|
|
16
|
+
import type { State } from "../state/open.ts";
|
|
17
|
+
import { tallyOf } from "./tally.ts";
|
|
18
|
+
import { checkBaseAfterMerge } from "./base-check.ts";
|
|
19
|
+
import { settleMergedPulls } from "./merged.ts";
|
|
20
|
+
import { readHistory } from "../adapters/history.ts";
|
|
21
|
+
import { gitIn, PATCH } from "../adapters/git.ts";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
import { configuredModelCall, modelCallOver } from "../adapters/model-call.ts";
|
|
24
|
+
import { MemoryFormatError, readMemory, unusedEntries, useOf } from "../loop/memory.ts";
|
|
25
|
+
import { runLoopPass, type LoopPass } from "../loop/pass.ts";
|
|
26
|
+
import { modelProposer, trustsRepeats } from "../loop/pair.ts";
|
|
27
|
+
import { measureOf } from "../measure/measure.ts";
|
|
28
|
+
import { measureInputsOf } from "../measure/inputs.ts";
|
|
29
|
+
import { readStatus, writeHeartbeat, writeStatus } from "../status/file.ts";
|
|
30
|
+
import { emptyStatus, type Status } from "../status/format.ts";
|
|
31
|
+
import { newestChoices, openQuestions } from "../status/sections.ts";
|
|
32
|
+
import { commandTimeoutMs } from "../exec.ts";
|
|
33
|
+
import { SECOND_MS } from "../time.ts";
|
|
34
|
+
import { type Exit, runLifecycle, type TickResult } from "./lifecycle.ts";
|
|
35
|
+
import { type Footprint, footprintOf, pick, PrefixGate } from "./scheduler.ts";
|
|
36
|
+
import { type Signature, signatureOf } from "./signature.ts";
|
|
37
|
+
import type { PullRequests } from "../adapters/pull-requests.ts";
|
|
38
|
+
import type { SlotPool } from "../slots/pool.ts";
|
|
39
|
+
import { type AnswerScope, settleAnswers } from "./answers.ts";
|
|
40
|
+
import { recentlyAsked, releaseQuestions } from "./questions.ts";
|
|
41
|
+
import { OWNER_APPROVAL } from "../decide/merge.ts";
|
|
42
|
+
import { answerTo, type Checkout, claimTtlMs, DEFAULT_BASE, endedStuck, park, rememberKinds, RUN_AGAIN, runThinPath, type ThinResult, waitsOnOwner } from "./thin-path.ts";
|
|
43
|
+
|
|
44
|
+
export type { TickResult } from "./lifecycle.ts";
|
|
45
|
+
|
|
46
|
+
/** Where the loop keeps the base it read, so a fetch elsewhere cannot move it mid-pass. */
|
|
47
|
+
const LOOP_REF = "refs/hum/loop-base";
|
|
48
|
+
|
|
49
|
+
export type WorkerOptions = {
|
|
50
|
+
/** The owner's checkout: its lockfile, `.hum/` and `adapters/` are what the update check watches. */
|
|
51
|
+
readonly repo: string;
|
|
52
|
+
readonly state: State;
|
|
53
|
+
readonly config: Config;
|
|
54
|
+
readonly adapters: {
|
|
55
|
+
readonly workSource: WorkSource;
|
|
56
|
+
readonly questions: Questions;
|
|
57
|
+
readonly answers?: Answers;
|
|
58
|
+
};
|
|
59
|
+
readonly runner: Runner;
|
|
60
|
+
/** The cheap model call; by default the config's decision model through the runner. */
|
|
61
|
+
readonly judge?: ModelCall;
|
|
62
|
+
readonly remote: string;
|
|
63
|
+
readonly base?: string;
|
|
64
|
+
readonly checks: readonly string[];
|
|
65
|
+
readonly holder: string;
|
|
66
|
+
readonly workDir?: string;
|
|
67
|
+
/** Gives each pass its working copy; by default a `git clone`. */
|
|
68
|
+
readonly checkout?: Checkout;
|
|
69
|
+
/** The run slots behind `checkout`, if any: each tick asks them to keep slots ready. */
|
|
70
|
+
readonly slots?: Pick<SlotPool, "keepReady">;
|
|
71
|
+
readonly dir?: string;
|
|
72
|
+
readonly where?: "mac" | "ci";
|
|
73
|
+
readonly now?: () => number;
|
|
74
|
+
/** The engine this process runs; the update check compares the one installed in `repo` with it. */
|
|
75
|
+
readonly engineVersion?: string;
|
|
76
|
+
/** The newest published version; a failed or slow read shows no version. */
|
|
77
|
+
readonly latestVersion?: () => Promise<string | undefined>;
|
|
78
|
+
/** When the scheduled workflow last ran; a failed or slow read shows no time. */
|
|
79
|
+
readonly ciTick?: () => Promise<number | undefined>;
|
|
80
|
+
readonly gate?: PrefixGate;
|
|
81
|
+
readonly onResult?: (result: ThinResult) => void;
|
|
82
|
+
/** The remote's pull requests and branch rules, for a remote on GitHub. */
|
|
83
|
+
readonly pulls?: PullRequests;
|
|
84
|
+
/** What the review-note loop reads from the review surface and CI; without it the loop reads only git and the owner's answers. */
|
|
85
|
+
readonly loop?: Partial<Pick<LoopPass, "comments" | "ciLogs">>;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** What the tick read of its sources: whether the watch saw a change, and the ready list. */
|
|
89
|
+
type Sources = {
|
|
90
|
+
readonly changed: boolean;
|
|
91
|
+
readonly ready: ItemRef[];
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
type Known = {
|
|
95
|
+
readonly footprint: Footprint;
|
|
96
|
+
readonly title: string;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
type InFlight = {
|
|
100
|
+
readonly abort: AbortController;
|
|
101
|
+
readonly since: number;
|
|
102
|
+
readonly known: Known;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const ERROR_EXCERPT = 300;
|
|
106
|
+
const UNREAD_CODE = "item-unread";
|
|
107
|
+
|
|
108
|
+
/** Reads `read` at most once per `everyMs`; a failed read, or one slower than `timeoutMs`, shows no value, and that too is kept for the period. */
|
|
109
|
+
const readEvery = <T>(read: (() => Promise<T | undefined>) | undefined, { everyMs, timeoutMs }: { everyMs: number; timeoutMs: number }): (() => Promise<T | undefined>) =>
|
|
110
|
+
read === undefined
|
|
111
|
+
? async () => undefined
|
|
112
|
+
: pMemoize(() => pTimeout(read(), { milliseconds: timeoutMs, fallback: () => undefined }).catch(() => undefined), { cache: new ExpiryMap(everyMs) });
|
|
113
|
+
|
|
114
|
+
/** Sources that never settle, so a restored item can be stepped by its timers without starting a run. */
|
|
115
|
+
const neverSources = (kind: Kind) =>
|
|
116
|
+
Object.fromEntries(Object.values(kind.machine.states).flatMap((node) => (node.invoke ? [[node.invoke.src, createAsyncLogic({ run: () => new Promise<never>(() => {}) })]] : [])));
|
|
117
|
+
|
|
118
|
+
/** The declared delays of the state an item was saved in, shortest first. */
|
|
119
|
+
const delaysOf = (kind: Kind, saved: SavedSnapshot): number[] =>
|
|
120
|
+
Object.keys((saved.state && kind.machine.states[saved.state]?.after) || {})
|
|
121
|
+
.map(Number)
|
|
122
|
+
.sort((a, b) => a - b);
|
|
123
|
+
|
|
124
|
+
const isAnsweredSince = (answeredAt: number | undefined, since: number): boolean => answeredAt !== undefined && answeredAt > since;
|
|
125
|
+
|
|
126
|
+
type DueWait = {
|
|
127
|
+
readonly saved: SavedSnapshot;
|
|
128
|
+
readonly kind: Kind;
|
|
129
|
+
readonly delays: readonly number[];
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const isDue = ({ saved, kind, delays }: DueWait, t: number): boolean =>
|
|
133
|
+
saved.machineVersion === kind.machine.version && delays.length > 0 && t >= saved.savedAt + Math.min(...delays);
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The worker. Each tick reads its facts once, then decides: it fires waits whose deadline has passed, renews claims,
|
|
137
|
+
* compares the engine and config with those at start, picks which items start, and writes a heartbeat and the status
|
|
138
|
+
* file. Runs go side by side, each a thin-path run on its own clone.
|
|
139
|
+
*/
|
|
140
|
+
export class Worker {
|
|
141
|
+
readonly #o: WorkerOptions;
|
|
142
|
+
readonly #now: () => number;
|
|
143
|
+
readonly #start: Signature;
|
|
144
|
+
readonly #gate: PrefixGate;
|
|
145
|
+
readonly #pool = new PQueue();
|
|
146
|
+
#loopAt = Number.NEGATIVE_INFINITY;
|
|
147
|
+
readonly #inFlight = new Map<string, InFlight>();
|
|
148
|
+
/** Items the owner answered that have not started yet; kept across ticks, because the watch token moves on. */
|
|
149
|
+
readonly #answered = new Set<string>();
|
|
150
|
+
/** Saved changes that land again under this worker's config before anything else starts. */
|
|
151
|
+
readonly #relanding = new Set<string>();
|
|
152
|
+
/** Items whose thread a tick failed to read; the next tick reads them again whatever the watch says. */
|
|
153
|
+
readonly #unread = new Set<string>();
|
|
154
|
+
readonly #merged: Status["merged"] = [];
|
|
155
|
+
readonly #wakes = new EventTarget();
|
|
156
|
+
readonly #latest: () => Promise<string | undefined>;
|
|
157
|
+
readonly #ciTick: () => Promise<number | undefined>;
|
|
158
|
+
readonly #learn: (id: string) => Promise<Known>;
|
|
159
|
+
readonly #judge: ModelCall;
|
|
160
|
+
#watchToken: string | undefined;
|
|
161
|
+
/** Set while the worker has seen an update; no change lands until a worker on the new config takes it. */
|
|
162
|
+
#updating: string | undefined;
|
|
163
|
+
|
|
164
|
+
get config(): Config {
|
|
165
|
+
return this.#o.config;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
constructor(options: WorkerOptions) {
|
|
169
|
+
this.#o = options;
|
|
170
|
+
this.#now = options.now ?? Date.now;
|
|
171
|
+
this.#gate = options.gate ?? new PrefixGate({ now: this.#now });
|
|
172
|
+
const timeoutMs = options.config.hum.statusReadTimeoutSeconds * SECOND_MS;
|
|
173
|
+
|
|
174
|
+
this.#latest = readEvery(options.latestVersion, { everyMs: options.config.hum.latestVersionCacheSeconds * SECOND_MS, timeoutMs });
|
|
175
|
+
this.#ciTick = readEvery(options.ciTick, { everyMs: options.config.hum.ciTickCacheSeconds * SECOND_MS, timeoutMs });
|
|
176
|
+
this.#start = signatureOf(options.repo, options.engineVersion ?? ENGINE_VERSION, options.config.hum.itemsDir);
|
|
177
|
+
this.#learn = pMemoize(async (id: string): Promise<Known> => {
|
|
178
|
+
const item = await options.adapters.workSource.read(id);
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
footprint: footprintOf(item),
|
|
182
|
+
|
|
183
|
+
title: item.title,
|
|
184
|
+
};
|
|
185
|
+
});
|
|
186
|
+
this.#judge = options.judge ?? configuredModelCall(options.runner, options.config.hum, (item, tokens) => tallyOf(options.state, item).spend(tokens));
|
|
187
|
+
rememberKinds(options.state, options.config);
|
|
188
|
+
this.#recheckLandings();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* A config can change a saved change's level, so each one lands again at this worker's first tick under the config
|
|
193
|
+
* it started with, claimed or not: a pull request armed under the old level is disarmed before GitHub merges it.
|
|
194
|
+
*/
|
|
195
|
+
#recheckLandings(): void {
|
|
196
|
+
const { state } = this.#o;
|
|
197
|
+
|
|
198
|
+
for (const { item } of state.landings.list()) {
|
|
199
|
+
if (state.parked.get(item)?.why === "review") this.#unpark(item, undefined);
|
|
200
|
+
|
|
201
|
+
this.#relanding.add(item);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
running(): string[] {
|
|
206
|
+
return [...this.#inFlight.keys()];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
idle(): Promise<void> {
|
|
210
|
+
return this.#pool.onIdle();
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Asks a serving worker for a tick now: a run ended, or an answer arrived. */
|
|
214
|
+
wake(): void {
|
|
215
|
+
this.#wakes.dispatchEvent(new Event("wake"));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#kindNamed(machineId: string): { readonly name: string; readonly kind: Kind } | undefined {
|
|
219
|
+
const found = Object.entries(this.#o.config.kinds).find(([, kind]) => kind.machine.id === machineId);
|
|
220
|
+
|
|
221
|
+
return found && { name: found[0], kind: found[1] };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether the item waits on the owner in its saved state. */
|
|
225
|
+
#isAsleep(saved: SavedSnapshot): boolean {
|
|
226
|
+
const kind = this.#kindNamed(saved.kind)?.kind;
|
|
227
|
+
|
|
228
|
+
return kind !== undefined && waitsOnOwner(kind, saved.state);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
#dueWaits(t: number): DueWait[] {
|
|
232
|
+
const waits = this.#o.state.items.saved().flatMap((saved) => {
|
|
233
|
+
const kind = this.#kindNamed(saved.kind)?.kind;
|
|
234
|
+
|
|
235
|
+
return kind && !this.#inFlight.has(saved.itemId) ? [{ saved, kind, delays: delaysOf(kind, saved) }] : [];
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
return waits.filter((wait) => isDue(wait, t));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* A saved wait whose deadline has passed fires now. The restored machine schedules its timers on the wall clock, so
|
|
243
|
+
* the clock given here only collects them, and the earliest ones, as many as the declared delays say are due by the
|
|
244
|
+
* worker's clock, fire.
|
|
245
|
+
*/
|
|
246
|
+
async #fireDue({ saved, kind, delays }: DueWait, t: number): Promise<void> {
|
|
247
|
+
const { state } = this.#o;
|
|
248
|
+
const timers: { fire: () => void; ms: number }[] = [];
|
|
249
|
+
const clock = { setTimeout: (fire: () => void, ms: number) => timers.push({ fire, ms }), clearTimeout: () => {} };
|
|
250
|
+
const restored = await state.items.restore(saved.itemId, kind, { sources: neverSources(kind), clock });
|
|
251
|
+
|
|
252
|
+
if (!restored.ok || !restored.value) return;
|
|
253
|
+
|
|
254
|
+
const actor = restored.value;
|
|
255
|
+
|
|
256
|
+
actor.start();
|
|
257
|
+
|
|
258
|
+
const dueCount = delays.filter((delay) => t - saved.savedAt >= delay).length;
|
|
259
|
+
|
|
260
|
+
for (const timer of timers.sort((a, b) => a.ms - b.ms).slice(0, dueCount)) timer.fire();
|
|
261
|
+
|
|
262
|
+
await Bun.sleep(0);
|
|
263
|
+
|
|
264
|
+
const value = String(actor.getSnapshot().value);
|
|
265
|
+
|
|
266
|
+
if (value !== saved.state) {
|
|
267
|
+
state.items.save(saved.itemId, kind, persistedSnapshot(actor));
|
|
268
|
+
|
|
269
|
+
if (endedStuck(kind, value))
|
|
270
|
+
park(
|
|
271
|
+
{ state, now: this.#now },
|
|
272
|
+
{
|
|
273
|
+
outcome: "stuck",
|
|
274
|
+
item: saved.itemId,
|
|
275
|
+
detail: `its wait in ${saved.state} timed out`,
|
|
276
|
+
},
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
actor.stop();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The item ids the answer hook dropped in the inbox folder. Each file is read once and removed. */
|
|
284
|
+
#inbox(): string[] {
|
|
285
|
+
return listFiles(this.#o.state.inbox).flatMap((file) => {
|
|
286
|
+
try {
|
|
287
|
+
const id = readFileSync(file, "utf8").trim();
|
|
288
|
+
|
|
289
|
+
rmSync(file, { force: true });
|
|
290
|
+
|
|
291
|
+
return id ? [id] : [];
|
|
292
|
+
} catch {
|
|
293
|
+
return [];
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Takes an item the owner acted on back from the parked. A finished change keeps its saved landing and lands again,
|
|
300
|
+
* unless the owner asked to run it again; otherwise its saved state is dropped and its cap starts afresh.
|
|
301
|
+
*/
|
|
302
|
+
#unpark(id: string, option: string | undefined): void {
|
|
303
|
+
const { state } = this.#o;
|
|
304
|
+
const parked = state.parked.get(id);
|
|
305
|
+
|
|
306
|
+
if (!parked) return;
|
|
307
|
+
|
|
308
|
+
state.parked.remove(id);
|
|
309
|
+
state.faults.clear(`item-${parked.why}:${id}`);
|
|
310
|
+
|
|
311
|
+
const landsAgain = state.landings.get(id) !== undefined && option !== RUN_AGAIN;
|
|
312
|
+
|
|
313
|
+
if (landsAgain) return;
|
|
314
|
+
|
|
315
|
+
state.items.remove(id);
|
|
316
|
+
state.landings.remove(id);
|
|
317
|
+
|
|
318
|
+
const spent = state.spent.get(id);
|
|
319
|
+
|
|
320
|
+
if (spent) state.spent.put(id, { ...spent, base: spent.total });
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Where an item stands when its thread is read, for the disposition of an answer to it. */
|
|
324
|
+
#stageOf(id: string, ready: boolean, sleeping: ReadonlyMap<string, SavedSnapshot>): AnswerScope {
|
|
325
|
+
const parked = this.#o.state.parked.get(id);
|
|
326
|
+
|
|
327
|
+
if (this.#inFlight.has(id)) return { stage: "running" };
|
|
328
|
+
|
|
329
|
+
if (parked) return { stage: parked.why === "review" ? "approval" : "waiting", options: parked.why === "review" ? [OWNER_APPROVAL, RUN_AGAIN] : [RUN_AGAIN] };
|
|
330
|
+
|
|
331
|
+
const asleep = sleeping.get(id);
|
|
332
|
+
const kind = asleep && this.#kindNamed(asleep.kind)?.kind;
|
|
333
|
+
|
|
334
|
+
if (asleep && kind) return { stage: kind.machine.states[asleep.state ?? ""]?.on?.["owner-approved"] ? "approval" : "waiting" };
|
|
335
|
+
|
|
336
|
+
return { stage: ready ? "waiting" : "ended" };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The tick's read of its sources: the watch first, so the ready list read after it holds every change the token
|
|
341
|
+
* names, then the ready list, whose read every later call of the tick shares. Undefined when a source could not be
|
|
342
|
+
* read, and its guard has raised the card.
|
|
343
|
+
*/
|
|
344
|
+
async #readSources(): Promise<Sources | undefined> {
|
|
345
|
+
const { adapters } = this.#o;
|
|
346
|
+
|
|
347
|
+
try {
|
|
348
|
+
const watched = adapters.answers ? await adapters.answers.watch(this.#watchToken) : { token: "", changed: true };
|
|
349
|
+
|
|
350
|
+
this.#watchToken = watched.token;
|
|
351
|
+
|
|
352
|
+
return { changed: watched.changed, ready: await adapters.workSource.listReady() };
|
|
353
|
+
} catch {
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Reads the threads that can have changed, settles each new answer, and releases a parked item the owner answered.
|
|
360
|
+
* Each item is read on its own: one that fails raises a card naming it and is read again next tick, and the rest go on.
|
|
361
|
+
*/
|
|
362
|
+
async #readAnswers(sleeping: readonly SavedSnapshot[], changed: boolean): Promise<void> {
|
|
363
|
+
const { state, adapters, config } = this.#o;
|
|
364
|
+
const inbox = this.#inbox();
|
|
365
|
+
|
|
366
|
+
if (!changed && inbox.length === 0 && this.#unread.size === 0) return;
|
|
367
|
+
|
|
368
|
+
const waiting = new Set(sleeping.map((s) => s.itemId));
|
|
369
|
+
const asleep = new Map(sleeping.map((s) => [s.itemId, s]));
|
|
370
|
+
const parked = state.parked.list();
|
|
371
|
+
const asked = recentlyAsked({ state, config, now: this.#now });
|
|
372
|
+
|
|
373
|
+
await Promise.all(
|
|
374
|
+
[...new Set([...waiting, ...parked.map((p) => p.item), ...inbox, ...asked, ...this.#unread])].map((id) =>
|
|
375
|
+
this.#readThread(id, async () => {
|
|
376
|
+
const raw = await adapters.workSource.read(id);
|
|
377
|
+
const item = await settleAnswers({ state, workSource: adapters.workSource, judge: this.#judge, now: this.#now }, raw, this.#stageOf(id, raw.ready, asleep));
|
|
378
|
+
const held = parked.find((p) => p.item === id);
|
|
379
|
+
const lastAnswer = item.thread.findLast((e) => e.kind === "answer");
|
|
380
|
+
const lastAnswerAt = lastAnswer?.at;
|
|
381
|
+
|
|
382
|
+
if (held) {
|
|
383
|
+
if (isAnsweredSince(lastAnswerAt, held.since)) this.#unpark(id, lastAnswer?.option);
|
|
384
|
+
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const hasNewAnswer = waiting.has(id) && answerTo(item) !== undefined && lastAnswerAt !== undefined;
|
|
389
|
+
|
|
390
|
+
if (hasNewAnswer) {
|
|
391
|
+
state.events.add({
|
|
392
|
+
source: "thread",
|
|
393
|
+
sourceId: `answer:${lastAnswerAt}`,
|
|
394
|
+
itemId: id,
|
|
395
|
+
type: "answered",
|
|
396
|
+
payload: {},
|
|
397
|
+
});
|
|
398
|
+
this.#answered.add(id);
|
|
399
|
+
}
|
|
400
|
+
}),
|
|
401
|
+
),
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Runs one item's read; a failure raises the card that names the item, and the item is read again next tick. */
|
|
406
|
+
async #readThread(id: string, read: () => Promise<void>): Promise<void> {
|
|
407
|
+
const { faults } = this.#o.state;
|
|
408
|
+
|
|
409
|
+
try {
|
|
410
|
+
await read();
|
|
411
|
+
this.#unread.delete(id);
|
|
412
|
+
faults.clear(`${UNREAD_CODE}:${id}`);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
this.#unread.add(id);
|
|
415
|
+
faults.raise({ code: UNREAD_CODE, item: id, cause: `The thread of ${id} could not be read: ${error instanceof Error ? error.message : String(error)}`.slice(0, ERROR_EXCERPT), fix: "hum reads it again each tick and goes on with the other items." });
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Every claim in flight is renewed; a run whose claim is gone stops. */
|
|
420
|
+
async #renew(): Promise<void> {
|
|
421
|
+
const { adapters, holder, config } = this.#o;
|
|
422
|
+
|
|
423
|
+
await Promise.all(
|
|
424
|
+
[...this.#inFlight].map(async ([id, run]) => {
|
|
425
|
+
const claim = await adapters.workSource.renew(id, holder, claimTtlMs(config)).catch(() => undefined);
|
|
426
|
+
|
|
427
|
+
if (claim?.won === false) run.abort.abort();
|
|
428
|
+
}),
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
#begin(id: string, known: Known, t: number): void {
|
|
433
|
+
const { state, config, adapters } = this.#o;
|
|
434
|
+
const abort = new AbortController();
|
|
435
|
+
|
|
436
|
+
this.#inFlight.set(id, { abort, since: t, known });
|
|
437
|
+
void this.#pool.add(() =>
|
|
438
|
+
runThinPath({
|
|
439
|
+
workSource: adapters.workSource,
|
|
440
|
+
questions: adapters.questions,
|
|
441
|
+
state,
|
|
442
|
+
runner: this.#o.runner,
|
|
443
|
+
judge: this.#judge,
|
|
444
|
+
config,
|
|
445
|
+
remote: this.#o.remote,
|
|
446
|
+
base: this.#o.base,
|
|
447
|
+
checks: this.#o.checks,
|
|
448
|
+
holder: this.#o.holder,
|
|
449
|
+
workDir: this.#o.workDir,
|
|
450
|
+
checkout: this.#o.checkout,
|
|
451
|
+
dir: this.#o.dir,
|
|
452
|
+
itemId: id,
|
|
453
|
+
signal: abort.signal,
|
|
454
|
+
gate: this.#gate,
|
|
455
|
+
now: this.#now,
|
|
456
|
+
pulls: this.#o.pulls,
|
|
457
|
+
mayLand: () => this.#updating === undefined,
|
|
458
|
+
}).then(
|
|
459
|
+
(result) => this.#ended(id, known, result),
|
|
460
|
+
(error: Error) => this.#failed(id, error),
|
|
461
|
+
),
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
#ended(id: string, known: Known, result: ThinResult): void {
|
|
466
|
+
this.#inFlight.delete(id);
|
|
467
|
+
|
|
468
|
+
if (result.outcome === "merged")
|
|
469
|
+
this.#merged.unshift({
|
|
470
|
+
item: id,
|
|
471
|
+
title: known.title,
|
|
472
|
+
mergedAt: this.#now(),
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
if (result.outcome === "merged") void this.#pool.add(() => this.#checkBase(id));
|
|
476
|
+
|
|
477
|
+
this.#o.onResult?.(result);
|
|
478
|
+
this.wake();
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** After a merge, the repo's checks run on the base; a failure there files a follow-up and joins the fix limit. */
|
|
482
|
+
async #checkBase(item: string): Promise<void> {
|
|
483
|
+
const { state, config, adapters, repo, remote, base = DEFAULT_BASE, checks } = this.#o;
|
|
484
|
+
|
|
485
|
+
await checkBaseAfterMerge({ state, config, workSource: adapters.workSource, git: gitIn(repo, { timeoutMs: commandTimeoutMs(config.hum) }), remote, base, checks, now: this.#now, item }).catch((error: Error) => {
|
|
486
|
+
state.faults.raise({ code: "base-check", item, cause: `The checks on ${base} after ${item} merged did not run: ${error.message}`.slice(0, ERROR_EXCERPT), fix: "hum does not look at that merge again; run the checks on the base yourself." });
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** The memory.md rules the runs shown the file did not apply in the last `memoryUnusedRuns` of them. */
|
|
491
|
+
#unusedMemory(): string[] {
|
|
492
|
+
const { state, config, repo } = this.#o;
|
|
493
|
+
|
|
494
|
+
try {
|
|
495
|
+
const { runsSoFar, lastUsed } = useOf(state.runs.all());
|
|
496
|
+
|
|
497
|
+
return unusedEntries(readMemory(join(repo, ".hum", "memory.md")), lastUsed, runsSoFar, config.hum.memoryUnusedRuns).map(({ rule }) => rule);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (!(error instanceof MemoryFormatError)) throw error;
|
|
500
|
+
|
|
501
|
+
state.faults.raise({ code: "memory-format", cause: error.message.slice(0, ERROR_EXCERPT), fix: "Give the line a source, as in - <rule> (source: <where you said it>)." });
|
|
502
|
+
|
|
503
|
+
return [];
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** The review-note loop runs once an interval, off the tick, so a slow model call never holds a tick. */
|
|
508
|
+
#loopIfDue(t: number): void {
|
|
509
|
+
const { state, config } = this.#o;
|
|
510
|
+
|
|
511
|
+
if (t - this.#loopAt < config.hum.loopIntervalSeconds * SECOND_MS) return;
|
|
512
|
+
|
|
513
|
+
this.#loopAt = t;
|
|
514
|
+
void this.#pool.add(() =>
|
|
515
|
+
this.#runLoop().catch((error: Error) => {
|
|
516
|
+
state.faults.raise({ code: "review-loop", cause: `The review-note loop failed: ${error.message}`.slice(0, ERROR_EXCERPT), fix: "It runs again next interval; look at the cause if this card stays." });
|
|
517
|
+
}),
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async #runLoop(): Promise<void> {
|
|
522
|
+
const { state, config, adapters, repo, remote, base = DEFAULT_BASE, runner, pulls, loop } = this.#o;
|
|
523
|
+
const git = gitIn(repo, { timeoutMs: commandTimeoutMs(config.hum) });
|
|
524
|
+
const call = modelCallOver(runner, { model: config.hum.decisionModel, timeoutMs: config.hum.modelCallTimeoutSeconds * SECOND_MS, trusts: () => true, onSpent: (item, tokens) => tallyOf(state, item).spend(tokens) });
|
|
525
|
+
|
|
526
|
+
await git.raw(["fetch", "-q", remote, `+refs/heads/${base}:${LOOP_REF}`]);
|
|
527
|
+
|
|
528
|
+
const tip = (await git.raw(["rev-parse", LOOP_REF])).trim();
|
|
529
|
+
|
|
530
|
+
if (pulls) await settleMergedPulls(state, pulls, this.#now());
|
|
531
|
+
|
|
532
|
+
await runLoopPass({
|
|
533
|
+
state,
|
|
534
|
+
config,
|
|
535
|
+
workSource: adapters.workSource,
|
|
536
|
+
now: this.#now,
|
|
537
|
+
comments: loop?.comments ?? (async () => []),
|
|
538
|
+
ciLogs: loop?.ciLogs ?? (async () => []),
|
|
539
|
+
history: () => readHistory(git, tip, config.hum),
|
|
540
|
+
hunkOf: async (sha, file) => (await git.run(["show", ...PATCH, "-U3", "--format=", sha, ...(file === undefined ? [] : ["--", file])])).stdout,
|
|
541
|
+
propose: modelProposer(call),
|
|
542
|
+
trusts: (models) => trustsRepeats(models, config.hum),
|
|
543
|
+
memoryPath: join(repo, ".hum", "memory.md"),
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
#failed(id: string, error: Error): void {
|
|
548
|
+
this.#inFlight.delete(id);
|
|
549
|
+
this.#o.state.faults.raise({
|
|
550
|
+
code: "run-error",
|
|
551
|
+
item: id,
|
|
552
|
+
cause: `The run for ${id} failed: ${error.message}`.slice(0, ERROR_EXCERPT),
|
|
553
|
+
fix: "hum tries the item again when its claim lapses; look at the cause if this card stays.",
|
|
554
|
+
});
|
|
555
|
+
this.wake();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async #stopRuns(): Promise<void> {
|
|
559
|
+
for (const run of this.#inFlight.values()) run.abort.abort();
|
|
560
|
+
|
|
561
|
+
await this.idle();
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** The heartbeat and the status file, both by temp file and rename. */
|
|
565
|
+
async #publish(t: number, signature: Signature, restarting: string | undefined): Promise<void> {
|
|
566
|
+
const { state, config, where = "mac" } = this.#o;
|
|
567
|
+
|
|
568
|
+
writeHeartbeat(state.heartbeatPath, {
|
|
569
|
+
time: t,
|
|
570
|
+
engineVersion: signature.engineVersion,
|
|
571
|
+
configHash: config.hash,
|
|
572
|
+
inFlight: this.running(),
|
|
573
|
+
intervalMs: config.hum.tickIntervalSeconds * SECOND_MS,
|
|
574
|
+
restarting,
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
const read = readStatus(state.statusPath);
|
|
578
|
+
const before = read.ok ? read.status : emptyStatus(signature.engineVersion, t);
|
|
579
|
+
const [latest, ci] = await Promise.all([this.#latest(), this.#ciTick()]);
|
|
580
|
+
const saved = new Map(state.items.saved().map((s) => [s.itemId, s.state]));
|
|
581
|
+
|
|
582
|
+
writeStatus(state.statusPath, {
|
|
583
|
+
...before,
|
|
584
|
+
writtenAt: t,
|
|
585
|
+
workers: { ...before.workers, ci: ci ?? before.workers.ci, [where]: t },
|
|
586
|
+
engine: {
|
|
587
|
+
version: signature.engineVersion,
|
|
588
|
+
adapterApi: ADAPTER_API_VERSION,
|
|
589
|
+
configSchema: SCHEMA_VERSION,
|
|
590
|
+
latest,
|
|
591
|
+
},
|
|
592
|
+
questions: openQuestions(state.questions.list(), state.answers.list()),
|
|
593
|
+
choices: newestChoices(state.choices.list(), config.hum.choicesShown),
|
|
594
|
+
cards: state.faults.list(),
|
|
595
|
+
inFlight: [...this.#inFlight].map(([item, run]) => ({
|
|
596
|
+
item,
|
|
597
|
+
title: run.known.title,
|
|
598
|
+
state: saved.get(item) ?? "starting",
|
|
599
|
+
since: run.since,
|
|
600
|
+
unclear: false,
|
|
601
|
+
})),
|
|
602
|
+
merged: [...this.#merged.splice(0), ...before.merged].slice(0, this.#o.config.hum.mergedShown),
|
|
603
|
+
possibleRepeats: state.possibleRepeats.list().map(({ a, b }) => ({ a, b })),
|
|
604
|
+
unusedMemory: this.#unusedMemory(),
|
|
605
|
+
measure: measureOf({ ...measureInputsOf(state), window: config.hum.measureWindow, globs: config.hum.paths.map(({ glob }) => glob) }) ?? null,
|
|
606
|
+
rules: state.learned.list().map(({ glob, level, item, at, commit }) => ({ glob, level, item, at, undo: { label: "Undo", command: `git revert ${commit}` } })),
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** Why the worker must restart: the installed engine, the lockfile, `.hum/` or `adapters/` differ from those at start. */
|
|
611
|
+
#updateSeen(now: Signature): string | undefined {
|
|
612
|
+
if (now.engineVersion !== this.#start.engineVersion) return `the engine changed from ${this.#start.engineVersion} to ${now.engineVersion}`;
|
|
613
|
+
|
|
614
|
+
if (now.hash !== this.#start.hash) return "the lockfile, .hum/ or adapters/ changed";
|
|
615
|
+
|
|
616
|
+
return undefined;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** The ready list, once the threads that changed were read; undefined when a source could not be read, and its guard has raised the card. */
|
|
620
|
+
async #readReady(sources: Sources | undefined, sleeping: readonly SavedSnapshot[]): Promise<ItemRef[] | undefined> {
|
|
621
|
+
if (sources === undefined) return undefined;
|
|
622
|
+
|
|
623
|
+
try {
|
|
624
|
+
await this.#readAnswers(sleeping, sources.changed);
|
|
625
|
+
|
|
626
|
+
return sources.ready;
|
|
627
|
+
} catch {
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** Which waiting items start now, by the scheduler's rules, and starts them. */
|
|
633
|
+
async #startPicked(t: number, ready: readonly ItemRef[], sleeping: readonly SavedSnapshot[]): Promise<string[]> {
|
|
634
|
+
const { state, runner, config } = this.#o;
|
|
635
|
+
const parked = new Set(state.parked.list().map((p) => p.item));
|
|
636
|
+
const asleep = new Set(sleeping.map((s) => s.itemId));
|
|
637
|
+
const isFresh = (id: string) => !this.#inFlight.has(id) && !parked.has(id) && !asleep.has(id);
|
|
638
|
+
const isAnsweredAndIdle = (id: string) => this.#answered.has(id) && !this.#inFlight.has(id);
|
|
639
|
+
const learned = (id: string) => this.#learn(id).catch(() => undefined);
|
|
640
|
+
|
|
641
|
+
const fresh = ready.flatMap((ref) => (isFresh(ref.id) ? [learned(ref.id).then((known) => ({ id: ref.id, answered: false, known }))] : []));
|
|
642
|
+
|
|
643
|
+
const answered = sleeping.flatMap((s) => {
|
|
644
|
+
const named = this.#kindNamed(s.kind);
|
|
645
|
+
|
|
646
|
+
return isAnsweredAndIdle(s.itemId) ? [learned(s.itemId).then((known) => ({ id: s.itemId, answered: true, known: known && named && { ...known, kind: named.name } }))] : [];
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
const relands = [...this.#relanding].flatMap((id) => (isFresh(id) && !ready.some((ref) => ref.id === id) ? [learned(id).then((known) => ({ id, answered: true, known }))] : []));
|
|
650
|
+
|
|
651
|
+
const waiting = (await Promise.all([...fresh, ...answered, ...relands])).flatMap(({ id, answered, known }) => (known ? [{ id, answered, known }] : []));
|
|
652
|
+
const knownOf = new Map(waiting.map((w) => [w.id, w.known]));
|
|
653
|
+
|
|
654
|
+
const { start } = pick({
|
|
655
|
+
now: t,
|
|
656
|
+
limitedUntil: runner.limitedUntil(),
|
|
657
|
+
runners: config.hum.runners,
|
|
658
|
+
running: [...this.#inFlight].map(([id, run]) => ({
|
|
659
|
+
id,
|
|
660
|
+
footprint: run.known.footprint,
|
|
661
|
+
})),
|
|
662
|
+
queue: waiting.map(({ id, answered, known }) => ({
|
|
663
|
+
id,
|
|
664
|
+
answered,
|
|
665
|
+
footprint: known.footprint,
|
|
666
|
+
})),
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
return start.flatMap(({ id }) => {
|
|
670
|
+
const known = knownOf.get(id);
|
|
671
|
+
|
|
672
|
+
if (!known) return [];
|
|
673
|
+
|
|
674
|
+
this.#answered.delete(id);
|
|
675
|
+
this.#relanding.delete(id);
|
|
676
|
+
this.#begin(id, known, t);
|
|
677
|
+
|
|
678
|
+
return [id];
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async tick(): Promise<TickResult> {
|
|
683
|
+
const { state, config } = this.#o;
|
|
684
|
+
const t = this.#now();
|
|
685
|
+
|
|
686
|
+
await Promise.all(this.#dueWaits(t).map((due) => this.#fireDue(due, t)));
|
|
687
|
+
|
|
688
|
+
if (config.hum.ciToken) checkTokenAge(state.faults, config.hum.ciToken.setUp, t, config.hum.tokenWarnDays);
|
|
689
|
+
|
|
690
|
+
const signature = signatureOf(this.#o.repo, this.#o.engineVersion ?? ENGINE_VERSION, this.#o.config.hum.itemsDir);
|
|
691
|
+
const update = this.#updateSeen(signature);
|
|
692
|
+
|
|
693
|
+
this.#updating = update;
|
|
694
|
+
const sleeping = state.items.saved().filter((s) => this.#isAsleep(s));
|
|
695
|
+
|
|
696
|
+
await this.#renew();
|
|
697
|
+
|
|
698
|
+
this.#o.slots?.keepReady();
|
|
699
|
+
|
|
700
|
+
if (update !== undefined) {
|
|
701
|
+
await this.#publish(t, signature, update);
|
|
702
|
+
|
|
703
|
+
return this.#inFlight.size === 0 ? { kind: "exit", reason: update } : { kind: "draining", reason: update };
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
const sources = await this.#readSources();
|
|
707
|
+
|
|
708
|
+
await releaseQuestions({ state, config, workSource: this.#o.adapters.workSource, questions: this.#o.adapters.questions, now: this.#now }).catch((error: Error) => {
|
|
709
|
+
state.faults.raise({ code: "question-release", cause: `Queued questions could not be asked: ${error.message}`.slice(0, ERROR_EXCERPT), fix: "hum asks them again on the next tick." });
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
this.#loopIfDue(t);
|
|
713
|
+
|
|
714
|
+
const ready = await this.#readReady(sources, sleeping);
|
|
715
|
+
const started = ready ? await this.#startPicked(t, ready, sleeping) : [];
|
|
716
|
+
|
|
717
|
+
await this.#publish(t, signature, undefined);
|
|
718
|
+
|
|
719
|
+
return { kind: "ran", started };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Ticks until an update is seen and the runs have ended, or `stop` fires. An end of a run, an inbox file or `wake` brings the next tick forward. */
|
|
723
|
+
async serve(stop?: AbortSignal): Promise<Exit> {
|
|
724
|
+
const { state, config } = this.#o;
|
|
725
|
+
|
|
726
|
+
mkdirSync(state.inbox, { recursive: true });
|
|
727
|
+
|
|
728
|
+
const life = runLifecycle(
|
|
729
|
+
{
|
|
730
|
+
tick: () => this.tick(),
|
|
731
|
+
stopRuns: () => this.#stopRuns(),
|
|
732
|
+
tickIntervalMs: config.hum.tickIntervalSeconds * SECOND_MS,
|
|
733
|
+
drainTimeoutMs: config.hum.drainTimeoutSeconds * SECOND_MS,
|
|
734
|
+
},
|
|
735
|
+
stop,
|
|
736
|
+
);
|
|
737
|
+
|
|
738
|
+
const wake = () => life.wake();
|
|
739
|
+
const inbox = watch(state.inbox, () => this.wake());
|
|
740
|
+
|
|
741
|
+
this.#wakes.addEventListener("wake", wake);
|
|
742
|
+
|
|
743
|
+
try {
|
|
744
|
+
return await life.ended;
|
|
745
|
+
} finally {
|
|
746
|
+
inbox.close();
|
|
747
|
+
this.#wakes.removeEventListener("wake", wake);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|