@evomap/evolver-cli 2.0.36 → 2.0.38

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 (40) hide show
  1. package/dist/antiGeneRollout.d.ts +2 -0
  2. package/dist/antiGeneRollout.js +21 -3
  3. package/dist/assetTrust.js +9 -0
  4. package/dist/atpAutoDeliver.d.ts +10 -0
  5. package/dist/atpAutoDeliver.js +28 -1
  6. package/dist/autoRecall.js +8 -4
  7. package/dist/autoexec.d.ts +15 -0
  8. package/dist/autoexec.js +148 -7
  9. package/dist/autoexecConfig.d.ts +1 -1
  10. package/dist/autoexecConfig.js +1 -1
  11. package/dist/cliContracts.d.ts +7 -2
  12. package/dist/cliContracts.js +97 -13
  13. package/dist/cursorRewrite.d.ts +6 -0
  14. package/dist/cursorRewrite.js +64 -6
  15. package/dist/cycleConsumer.js +1 -0
  16. package/dist/index.js +11 -3
  17. package/dist/localPublishBinding.d.ts +25 -0
  18. package/dist/localPublishBinding.js +139 -0
  19. package/dist/promptRecallHook.js +86 -10
  20. package/dist/recall.d.ts +2 -0
  21. package/dist/recall.js +19 -1
  22. package/dist/recipe.d.ts +5 -1
  23. package/dist/recipe.js +123 -42
  24. package/dist/referenceAccess.d.ts +3 -0
  25. package/dist/referenceAccess.js +232 -0
  26. package/dist/referencePublish.d.ts +4 -0
  27. package/dist/referencePublish.js +40 -0
  28. package/dist/requiredSandboxValidation.js +6 -1
  29. package/dist/reviewFilter.d.ts +1 -1
  30. package/dist/reviewFilter.js +12 -1
  31. package/dist/sourceQualification.d.ts +2 -0
  32. package/dist/sourceQualification.js +120 -0
  33. package/dist/taskCommitments.d.ts +135 -0
  34. package/dist/taskCommitments.js +492 -0
  35. package/dist/taskReceiver.d.ts +151 -0
  36. package/dist/taskReceiver.js +459 -0
  37. package/dist/thesis.d.ts +3 -0
  38. package/dist/thesis.js +122 -100
  39. package/dist/workflowRuntime.js +13 -2
  40. package/package.json +7 -7
@@ -0,0 +1,459 @@
1
+ /**
2
+ * taskReceiver — pulls tasks the Hub offers this node, scores them, claims the
3
+ * one worth doing, and shapes it for the execute queue.
4
+ *
5
+ * Ported from evolver v1 (`src/gep/taskReceiver.js`), which v2 dropped: the
6
+ * adapter kept `listMyTasks` but nothing could fetch, score, claim or complete,
7
+ * so a v2 node saw its tasks and could never take one.
8
+ */
9
+ import { randomUUID } from 'node:crypto';
10
+ import { AtpHubClient } from '@evomap/evolver-adapter-public';
11
+ import { createAtpClientFromEnv, resolveAtpSenderId } from './atp.js';
12
+ import { completionLedgerPath, defaultReadQueueTask, defaultWriteQueueTask, fileClaim, liveCommitments, rememberUnqueued, unsentCommitments, HUB_QUEUE_PREFIX, } from './taskCommitments.js';
13
+ export { COMPLETION_LEDGER_FILENAME, HUB_QUEUE_PREFIX, completionLedgerPath, hubTaskIdOf, readCompletionLedger, } from './taskCommitments.js';
14
+ export const TASK_STRATEGIES = ['greedy', 'balanced', 'conservative'];
15
+ const STRATEGY_WEIGHTS = {
16
+ greedy: { roi: 0.1, capability: 0.05, completion: 0.05, bounty: 0.8 },
17
+ balanced: { roi: 0.35, capability: 0.3, completion: 0.2, bounty: 0.15 },
18
+ conservative: { roi: 0.25, capability: 0.45, completion: 0.25, bounty: 0.05 },
19
+ };
20
+ const MIN_COMMITMENT_MS = 5 * 60_000;
21
+ const MAX_COMMITMENT_MS = 24 * 60 * 60_000;
22
+ const DEADLINE_SAFETY_MS = 60_000;
23
+ const DIFFICULTY_DURATION = [
24
+ { threshold: 0.3, durationMs: 15 * 60_000 },
25
+ { threshold: 0.5, durationMs: 30 * 60_000 },
26
+ { threshold: 0.7, durationMs: 60 * 60_000 },
27
+ { threshold: 1.0, durationMs: 120 * 60_000 },
28
+ ];
29
+ const ROI_REFERENCE = 200;
30
+ const BOUNTY_REFERENCE = 100;
31
+ const SIGNAL_SIMILARITY_FLOOR = 0.15;
32
+ const HISTORY_WINDOW = 200;
33
+ /**
34
+ * The node's own record of what it has finished, folded out of the cycle log: each terminal
35
+ * cycle joined to the signals that drove it. Without this, capability matching scores every
36
+ * task against an empty history and the strategy weights never touch a real decision.
37
+ */
38
+ export function memoryEventsFromCycleLog(events, window = HISTORY_WINDOW) {
39
+ const statusByCycle = new Map();
40
+ const signalsByCycle = new Map();
41
+ for (const event of events) {
42
+ const payload = event.payload && typeof event.payload === 'object' ? event.payload : null;
43
+ const cycleId = typeof payload?.['cycleId'] === 'string' ? payload['cycleId'] : null;
44
+ if (!cycleId)
45
+ continue;
46
+ if (event.type === 'cycle.solidified')
47
+ statusByCycle.set(cycleId, 'success');
48
+ else if (event.type === 'cycle.failed')
49
+ statusByCycle.set(cycleId, 'failed');
50
+ else if (event.type === 'cycle.signals_collected') {
51
+ const base = payload?.['baseSignals'] ?? payload?.['signals'];
52
+ if (Array.isArray(base))
53
+ signalsByCycle.set(cycleId, base.filter((signal) => typeof signal === 'string'));
54
+ }
55
+ }
56
+ return [...statusByCycle.entries()]
57
+ .slice(-window)
58
+ .map(([cycleId, status]) => ({ status, signals: signalsByCycle.get(cycleId) ?? [] }));
59
+ }
60
+ export function taskStrategy(env = process.env) {
61
+ const raw = String(env.TASK_STRATEGY ?? 'balanced').toLowerCase().trim();
62
+ return TASK_STRATEGIES.includes(raw) ? raw : 'balanced';
63
+ }
64
+ export function minCapabilityMatch(env = process.env) {
65
+ const parsed = Number(env.TASK_MIN_CAPABILITY_MATCH);
66
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0.1;
67
+ }
68
+ export function parseSignals(signals) {
69
+ if (Array.isArray(signals))
70
+ return signals.map((s) => String(s).trim().toLowerCase()).filter(Boolean);
71
+ if (typeof signals === 'string')
72
+ return signals.split(/[,|]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
73
+ return [];
74
+ }
75
+ function jaccard(left, right) {
76
+ if (left.length === 0 || right.length === 0)
77
+ return 0;
78
+ const a = new Set(left);
79
+ const b = new Set(right);
80
+ let shared = 0;
81
+ for (const value of a)
82
+ if (b.has(value))
83
+ shared += 1;
84
+ return shared / (a.size + b.size - shared);
85
+ }
86
+ /** How much this node's own history looks like the task, in [0, 1]. */
87
+ export function estimateCapabilityMatch(task, memoryEvents = []) {
88
+ const taskSignals = parseSignals(task.signals);
89
+ if (taskSignals.length === 0 || memoryEvents.length === 0)
90
+ return 0;
91
+ const seen = new Set();
92
+ const totals = new Map();
93
+ for (const event of memoryEvents) {
94
+ const signals = parseSignals(event.signals);
95
+ if (signals.length === 0)
96
+ continue;
97
+ for (const signal of signals)
98
+ seen.add(signal);
99
+ const key = signals.join('|');
100
+ const entry = totals.get(key) ?? { total: 0, success: 0 };
101
+ entry.total += 1;
102
+ if (event.status === 'success')
103
+ entry.success += 1;
104
+ totals.set(key, entry);
105
+ }
106
+ const overlap = jaccard(taskSignals, [...seen]);
107
+ let weighted = 0;
108
+ let weight = 0;
109
+ for (const [key, entry] of totals) {
110
+ const similarity = jaccard(taskSignals, key.split('|'));
111
+ if (similarity < SIGNAL_SIMILARITY_FLOOR)
112
+ continue;
113
+ // Laplace smoothing keeps a single lucky success from reading as certainty.
114
+ weighted += ((entry.success + 1) / (entry.total + 2)) * similarity;
115
+ weight += similarity;
116
+ }
117
+ const successScore = weight > 0 ? weighted / weight : 0.5;
118
+ return Math.min(1, overlap * 0.4 + successScore * 0.6);
119
+ }
120
+ export function localDifficultyEstimate(task) {
121
+ const signalFactor = Math.min(parseSignals(task.signals).length / 8, 1);
122
+ const words = String(task.title ?? '').split(/\s+/).filter(Boolean).length;
123
+ return Math.min(1, signalFactor * 0.6 + Math.min(words / 15, 1) * 0.4);
124
+ }
125
+ export function scoreTask(task, capabilityMatch, strategy = 'balanced') {
126
+ const weights = STRATEGY_WEIGHTS[strategy];
127
+ const difficulty = task.complexity_score ?? localDifficultyEstimate(task);
128
+ const bounty = task.bounty_amount ?? 0;
129
+ const completion = task.historical_completion_rate ?? 0.5;
130
+ const roi = Math.min(bounty / (difficulty + 0.1) / ROI_REFERENCE, 1);
131
+ const bountyNorm = Math.min(bounty / BOUNTY_REFERENCE, 1);
132
+ const composite = weights.roi * roi + weights.capability * capabilityMatch + weights.completion * completion + weights.bounty * bountyNorm;
133
+ return {
134
+ composite: round(composite, 3),
135
+ factors: { roi: round(roi, 2), capability: round(capabilityMatch, 2), completion: round(completion, 2), bounty: round(bountyNorm, 2), difficulty: round(difficulty, 2) },
136
+ };
137
+ }
138
+ function round(value, digits) {
139
+ const factor = 10 ** digits;
140
+ return Math.round(value * factor) / factor;
141
+ }
142
+ /**
143
+ * Pick what to work on. A task this node already holds always wins — finishing
144
+ * a commitment beats starting a better one.
145
+ */
146
+ export function selectBestTask(tasks, nodeId, memoryEvents = [], env = process.env) {
147
+ return rankTasks(tasks, nodeId, memoryEvents, env)[0] ?? null;
148
+ }
149
+ /**
150
+ * Every task worth trying, best first. A ranked list rather than one winner: the
151
+ * top candidate can turn out to be unusable — a lapsed commitment, a window too
152
+ * short to promise — and one bad head must not hide the rest of the batch.
153
+ */
154
+ export function rankTasks(tasks, nodeId, memoryEvents = [], env = process.env) {
155
+ const mine = tasks
156
+ .filter((task) => task.status === 'claimed' && task.claimed_by === nodeId)
157
+ .map((task) => ({ task, reason: 'resume' }));
158
+ const open = tasks.filter((task) => task.status === 'open');
159
+ const strategy = taskStrategy(env);
160
+ if (strategy === 'greedy' && memoryEvents.length === 0) {
161
+ const byBounty = [...open].sort((left, right) => Number(Boolean(right.bounty_id)) - Number(Boolean(left.bounty_id)) || (right.bounty_amount ?? 0) - (left.bounty_amount ?? 0));
162
+ return [...mine, ...byBounty.map((task) => ({ task, reason: 'scored', score: scoreTask(task, 0, strategy) }))];
163
+ }
164
+ const floor = minCapabilityMatch(env);
165
+ const scored = open
166
+ .map((task) => ({ task, reason: 'scored', score: scoreTask(task, estimateCapabilityMatch(task, memoryEvents), strategy) }))
167
+ .filter((entry) => entry.score.factors.capability >= floor || memoryEvents.length === 0)
168
+ .sort((left, right) => right.score.composite - left.score.composite);
169
+ return [...mine, ...scored];
170
+ }
171
+ /**
172
+ * What this node can honestly promise: harder tasks get longer, but never past
173
+ * the task's own expiry, and never a window too short to be worth claiming.
174
+ */
175
+ export function estimateCommitmentDeadline(task, now = Date.now()) {
176
+ const difficulty = task.complexity_score ?? localDifficultyEstimate(task);
177
+ const band = DIFFICULTY_DURATION.find((entry) => difficulty <= entry.threshold);
178
+ const durationMs = Math.max(MIN_COMMITMENT_MS, Math.min(MAX_COMMITMENT_MS, band?.durationMs ?? MAX_COMMITMENT_MS));
179
+ let deadline = now + durationMs;
180
+ if (task.expires_at) {
181
+ const expiresAt = Date.parse(task.expires_at);
182
+ if (Number.isFinite(expiresAt) && expiresAt < deadline) {
183
+ const adjusted = expiresAt - DEADLINE_SAFETY_MS;
184
+ if (adjusted - now < MIN_COMMITMENT_MS)
185
+ return null;
186
+ deadline = adjusted;
187
+ }
188
+ }
189
+ return new Date(deadline).toISOString();
190
+ }
191
+ const PRIVACY_OPEN = '[PRIVACY_PARAMS]';
192
+ const PRIVACY_CLOSE = '[/PRIVACY_PARAMS]';
193
+ /**
194
+ * A privacy task carries its parameters as a fenced block in the body. Ported
195
+ * from v1 `privacyClient.parsePrivacyParams`; the rest of that client (blob
196
+ * upload, sealed execution) has no v2 counterpart yet.
197
+ */
198
+ export function detectPrivacyTask(task) {
199
+ const body = task.body ?? task.description ?? '';
200
+ if (typeof body !== 'string')
201
+ return null;
202
+ const start = body.indexOf(PRIVACY_OPEN);
203
+ const end = body.indexOf(PRIVACY_CLOSE);
204
+ if (start === -1 || end === -1 || end <= start)
205
+ return null;
206
+ const params = new Map();
207
+ for (const line of body.slice(start + PRIVACY_OPEN.length, end).split('\n')) {
208
+ const trimmed = line.trim();
209
+ const colon = trimmed.indexOf(':');
210
+ if (colon === -1)
211
+ continue;
212
+ params.set(trimmed.slice(0, colon).trim(), trimmed.slice(colon + 1).trim());
213
+ }
214
+ const toolId = params.get('tool_id');
215
+ if (!toolId)
216
+ return null;
217
+ return { toolId, blobIds: (params.get('blob_ids') ?? '').split(',').map((id) => id.trim()).filter(Boolean) };
218
+ }
219
+ /** Signals an execute-queue task should carry so the loop knows what it is. */
220
+ export function taskToSignals(task) {
221
+ const signals = parseSignals(task.signals);
222
+ const fromTitle = String(task.title ?? '').toLowerCase().split(/[^a-z0-9_]+/).filter((word) => word.length > 3).slice(0, 5);
223
+ return [...new Set([...signals, ...fromTitle])];
224
+ }
225
+ /** Same signals, plus the two a sealed-tool task needs so the loop routes it. */
226
+ export function taskToSignalsWithPrivacy(task) {
227
+ const signals = taskToSignals(task);
228
+ if (!detectPrivacyTask(task))
229
+ return signals;
230
+ return [...new Set([...signals, 'privacy_computing', 'sealed_tool'])];
231
+ }
232
+ /**
233
+ * One receive pass: ask, choose, claim. Returns what the execute queue should
234
+ * run, or why nothing was taken.
235
+ */
236
+ export async function receiveTask(client, opts) {
237
+ const env = opts.env ?? process.env;
238
+ const now = opts.now ?? Date.now;
239
+ const fetched = await call(() => client.fetchTasks());
240
+ // A failed fetch is not an idle Hub. Saying "none" here hid a 401 behind silence.
241
+ if (!fetched.ok)
242
+ return { claimed: false, reason: 'fetch_failed', seen: 0, error: errorOf(fetched) };
243
+ // A task id lands in a queue filename: anything outside the safe charset (a `..`
244
+ // segment above all) would write outside the queue directory, so drop it here.
245
+ const offered = Array.isArray(fetched.data?.tasks) ? fetched.data.tasks : [];
246
+ const tasks = offered.map(normalizeHubTask).filter((task) => task !== null);
247
+ const seen = { seen: tasks.length, ...(offered.length > tasks.length ? { rejected: offered.length - tasks.length } : {}) };
248
+ let blocked = null;
249
+ for (const selection of rankTasks(tasks, opts.nodeId, opts.memoryEvents ?? [], env)) {
250
+ const taken = selection.reason === 'resume'
251
+ ? resumeClaim(selection, opts, now())
252
+ : await takeClaim(client, selection, opts, now());
253
+ if (taken.claimed)
254
+ return { ...taken, ...seen };
255
+ // One unusable head must not hide the rest of the batch: remember why, keep looking.
256
+ blocked ??= taken;
257
+ }
258
+ return blocked ? { ...blocked, ...seen } : { claimed: false, reason: 'none', ...seen };
259
+ }
260
+ /** A task this node already holds: no second claim, but the promise must still stand. */
261
+ function resumeClaim(selection, opts, nowMs) {
262
+ const held = opts.claimFor?.(`${HUB_QUEUE_PREFIX}${selection.task.task_id}`);
263
+ const deadline = held?.commitmentDeadline ?? commitmentDeadlineOf(selection.task);
264
+ // No record of the promise, and the Hub did not restate it. Inventing a fresh window
265
+ // here would make a commitment that lapsed weeks ago look alive on every restart, so
266
+ // the claim is not resumed — the Hub releases it at its own deadline either way.
267
+ if (!deadline) {
268
+ return { claimed: false, reason: 'expired', seen: 0, task: selection.task, commitmentDeadline: null };
269
+ }
270
+ const parsed = Date.parse(deadline);
271
+ if (Number.isFinite(parsed) && parsed <= nowMs) {
272
+ return { claimed: false, reason: 'expired', seen: 0, task: selection.task, commitmentDeadline: deadline };
273
+ }
274
+ // Resuming is the same filing, not a new one: keep the generation the claim was filed
275
+ // under, or a result from the run already in flight would look stale on return.
276
+ return { claimed: true, reason: 'resume', seen: 0, task: selection.task, score: selection.score, queueTask: queueTaskFor(selection.task, opts.repo, deadline, held?.generation ?? newGeneration()) };
277
+ }
278
+ /**
279
+ * The Hub's own view of how long it is holding a task for its claimant. Not `expires_at`:
280
+ * the bounty outlives the commitment by days, and resuming on it is how a node keeps
281
+ * working on something that was re-dispatched hours ago.
282
+ */
283
+ function commitmentDeadlineOf(task) {
284
+ const raw = task.commitment_deadline ?? null;
285
+ return typeof raw === 'string' && Number.isFinite(Date.parse(raw)) ? raw : null;
286
+ }
287
+ /** A task no one holds: promise a deadline this node can keep, then take it. */
288
+ async function takeClaim(client, selection, opts, nowMs) {
289
+ const commitmentDeadline = estimateCommitmentDeadline(selection.task, nowMs);
290
+ if (!commitmentDeadline) {
291
+ return { claimed: false, reason: 'no_deadline', seen: 0, task: selection.task, score: selection.score, commitmentDeadline: null };
292
+ }
293
+ const claim = await call(() => client.claimTask(selection.task.task_id, { commitmentDeadline }));
294
+ if (!claim.ok) {
295
+ return { claimed: false, reason: 'claim_failed', seen: 0, task: selection.task, score: selection.score, commitmentDeadline, error: errorOf(claim) };
296
+ }
297
+ return { claimed: true, reason: 'scored', seen: 0, task: selection.task, score: selection.score, commitmentDeadline, queueTask: queueTaskFor(selection.task, opts.repo, commitmentDeadline, newGeneration()) };
298
+ }
299
+ /** The execute-queue entry under this id, if the loop has not taken it yet. */
300
+ function queuedTask(queueDir, id) {
301
+ return defaultReadQueueTask(queueDir, id);
302
+ }
303
+ function newGeneration() {
304
+ return randomUUID().slice(0, 8);
305
+ }
306
+ function queueTaskFor(task, repo, commitmentDeadline, generation) {
307
+ return {
308
+ id: `${HUB_QUEUE_PREFIX}${task.task_id}`,
309
+ hubTaskId: task.task_id,
310
+ generation,
311
+ repo,
312
+ target: String(task.title ?? task.task_id).slice(0, 200),
313
+ expectedEffect: `complete hub task ${task.task_id}`,
314
+ signals: taskToSignalsWithPrivacy(task),
315
+ ...(commitmentDeadline ? { commitmentDeadline } : {}),
316
+ };
317
+ }
318
+ /** A thrown transport error is the same event as `{ ok: false }` and must read as one. */
319
+ async function call(rpc) {
320
+ try {
321
+ return await rpc();
322
+ }
323
+ catch (error) {
324
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
325
+ }
326
+ }
327
+ function errorOf(result) {
328
+ return result.error ?? `hub ${result.status ?? 0}`;
329
+ }
330
+ const SAFE_TASK_ID = /^[A-Za-z0-9_-]{1,128}$/;
331
+ export function isSafeTaskId(taskId) {
332
+ return typeof taskId === 'string' && SAFE_TASK_ID.test(taskId);
333
+ }
334
+ /**
335
+ * The Hub and the proxies in front of it serialize tasks either way, and the neighbouring
336
+ * `/a2a/task/my` reader already accepts both. Read one shape here so a camelCase response
337
+ * is not silently an empty task list.
338
+ */
339
+ export function normalizeHubTask(raw) {
340
+ if (!raw || typeof raw !== 'object')
341
+ return null;
342
+ const task = raw;
343
+ const pick = (...keys) => {
344
+ for (const key of keys)
345
+ if (task[key] !== undefined && task[key] !== null)
346
+ return task[key];
347
+ return undefined;
348
+ };
349
+ const taskId = pick('task_id', 'taskId');
350
+ if (!isSafeTaskId(taskId))
351
+ return null;
352
+ return {
353
+ ...task,
354
+ task_id: taskId,
355
+ ...(pick('claimed_by', 'claimedBy') === undefined ? {} : { claimed_by: pick('claimed_by', 'claimedBy') }),
356
+ ...(pick('bounty_amount', 'bountyAmount') === undefined ? {} : { bounty_amount: pick('bounty_amount', 'bountyAmount') }),
357
+ ...(pick('bounty_id', 'bountyId') === undefined ? {} : { bounty_id: pick('bounty_id', 'bountyId') }),
358
+ ...(pick('expires_at', 'expiresAt') === undefined ? {} : { expires_at: pick('expires_at', 'expiresAt') }),
359
+ ...(pick('commitment_deadline', 'commitmentDeadline') === undefined ? {} : { commitment_deadline: pick('commitment_deadline', 'commitmentDeadline') }),
360
+ ...(pick('complexity_score', 'complexityScore') === undefined ? {} : { complexity_score: pick('complexity_score', 'complexityScore') }),
361
+ ...(pick('historical_completion_rate', 'historicalCompletionRate') === undefined ? {} : { historical_completion_rate: pick('historical_completion_rate', 'historicalCompletionRate') }),
362
+ ...(pick('result_asset_id', 'resultAssetId') === undefined ? {} : { result_asset_id: pick('result_asset_id', 'resultAssetId') }),
363
+ };
364
+ }
365
+ const IDLE = { claimed: false, reason: 'none', seen: 0 };
366
+ export function isTaskReceiverEnabled(env = process.env) {
367
+ return String(env['EVOLVER_TASK_RECEIVER'] ?? 'on').toLowerCase().trim() !== '0';
368
+ }
369
+ function hubClientOrNull(env, deps) {
370
+ try {
371
+ return deps.client ?? createAtpClientFromEnv(env);
372
+ }
373
+ catch {
374
+ return null;
375
+ }
376
+ }
377
+ export function resolveTaskReceiver(env = process.env, deps = {}) {
378
+ const ledgerPath = deps.completionLedgerPath ?? completionLedgerPath(env);
379
+ const now = deps.now ?? (() => Date.now());
380
+ const write = deps.writeQueueTask ?? defaultWriteQueueTask;
381
+ // One identity, and it is the client's: filtering tasks as one node while claiming and
382
+ // completing them as another is how a node skips its own work and takes someone else's.
383
+ // With a client present its answer is final — an env or caller value is not bound to the
384
+ // credentials that will do the claiming, so it only stands in when there is no client.
385
+ const client = hubClientOrNull(env, deps);
386
+ const nodeId = client ? client.nodeId?.() : deps.nodeId ?? resolveAtpSenderId(env);
387
+ // A promise made in an earlier run outlives the switch, the identity and the process that
388
+ // made it, so the debt is carried on every wiring — receiving new work is what turns off.
389
+ const commitmentDeps = { ledgerPath, now, write, ...(deps.queueDir ? { queueDir: deps.queueDir } : {}) };
390
+ const commitments = client ? liveCommitments(client, commitmentDeps) : unsentCommitments(ledgerPath, now);
391
+ const off = (reason) => ({ enabled: false, reason, tick: async () => IDLE, ...commitments });
392
+ if (!isTaskReceiverEnabled(env))
393
+ return off('off');
394
+ if (!nodeId)
395
+ return off('no_node');
396
+ if (!client)
397
+ return off('client_error');
398
+ if (!deps.repo || !deps.queueDir)
399
+ return off('no_repo');
400
+ const repo = deps.repo;
401
+ const queueDir = deps.queueDir;
402
+ // Bound here so the pass below keeps the narrowing the guards above established.
403
+ const hub = client;
404
+ const node = nodeId;
405
+ // One pass at a time, whoever calls. Two overlapping passes both see a task as
406
+ // unclaimed, both claim it, and the Hub commitment ends up with two queue entries.
407
+ // autoexec happens to single-flight its tick; the guarantee belongs here, not there.
408
+ let inProgress = null;
409
+ return {
410
+ enabled: true,
411
+ ...commitments,
412
+ tick: async () => {
413
+ if (inProgress)
414
+ return inProgress;
415
+ inProgress = receivePass();
416
+ try {
417
+ return await inProgress;
418
+ }
419
+ finally {
420
+ inProgress = null;
421
+ }
422
+ },
423
+ };
424
+ async function receivePass() {
425
+ const received = await receiveTask(hub, { nodeId: node, repo, claimFor: commitments.claimFor, memoryEvents: deps.memoryEvents?.() ?? [], env, now: deps.now });
426
+ if (!received.claimed || !received.queueTask)
427
+ return received;
428
+ // Resuming is not re-filing. A claim already registered under this generation is
429
+ // either sitting in the queue or being executed right now; writing it again would
430
+ // either be read as a stranger's queue entry or hand the executor a duplicate.
431
+ // "Still in the loop's hands" is the queue entry OR a run already under way: the
432
+ // executor moves the file out of the queue when it starts, and re-filing then would
433
+ // hand it the same task twice.
434
+ const held = commitments.claimFor(received.queueTask.id);
435
+ const queued = queuedTask(queueDir, received.queueTask.id)?.generation === held?.generation;
436
+ const inFlight = deps.inFlight?.(received.queueTask.id) ?? false;
437
+ if (received.reason === 'resume' && held !== null && (queued || inFlight))
438
+ return received;
439
+ // We hold a claim the moment the Hub grants it. Anything that keeps the loop from
440
+ // seeing the task leaves the Hub waiting on work that cannot start, so the failure
441
+ // is written down and retried on later beats rather than dropped with the claim.
442
+ try {
443
+ const filed = fileClaim(commitmentDeps, queueDir, received.queueTask);
444
+ if (filed === 'name_taken' || filed === 'unrecorded') {
445
+ const why = filed === 'name_taken'
446
+ ? `queue id ${received.queueTask.id} is taken by another task`
447
+ : `ownership of ${received.queueTask.id} could not be recorded`;
448
+ rememberUnqueued(ledgerPath, received.queueTask, why);
449
+ return { ...received, claimed: false, reason: 'queue_failed', error: why };
450
+ }
451
+ }
452
+ catch (error) {
453
+ const reason = error instanceof Error ? error.message : String(error);
454
+ rememberUnqueued(ledgerPath, received.queueTask, reason);
455
+ return { ...received, claimed: false, reason: 'queue_failed', error: reason };
456
+ }
457
+ return received;
458
+ }
459
+ }
package/dist/thesis.d.ts CHANGED
@@ -28,6 +28,9 @@ type CycleExecute = (mutation: never, decision: {
28
28
  };
29
29
  };
30
30
  export interface ThesisCommandDeps {
31
+ env?: Readonly<NodeJS.ProcessEnv>;
32
+ provenance?: assetstore.ProvenanceStore;
33
+ review?: assetstore.ReviewLedger;
31
34
  /** evolver-arm store (the learned-gene pool). Default: the live asset store. */
32
35
  pool?: assetstore.AssetStoreProvider;
33
36
  /** Inject a deterministic agent for tests / a dry simulation. Default: makeSafeExecute against `--repo` (live). */